【发布时间】:2016-09-12 01:07:12
【问题描述】:
如果用户可以通过f.select在views/profiles/_form.html.erb 中声明他们的:buisness_type,我正在构建一个RailsApp。
然后在views/users/show.html.erb 中,current_user 可以在 input_field 中输入汽车行驶的值。
我想要做的是让 current_user 根据他们的 :buisness_type 过滤掉其他用户。因此 current_user 可以在 views/users/show.html.erb 中看到其他用户 car_trip 在同一 :business_type 中的平均值。
在views/profiles/_form.html.erb我有这个代码保存在Profile.rbmodel中:
<div class="form-group">
<%= f.label :buisness_type %>
<%= f.select(:buisness_type, grouped_options_for_select(Profile::BUISNESS_TYPES),{ :class => 'form-control' })%>
</div>
在views/users/show.html.erb 我正在渲染这个部分:
<%= form_for @transport, html: {class: 'form-horizontal'} do |f| %>
<div class="control-group">
<%= f.label :Transport_type, class: 'control-label' %><br>
<div class="controls">
<%= f.select(:transport_type, options_for_select(Transport::TRANSPORT_TYPES)) %>
</div>
</div>
<div class="control-group">
<%= f.label :Trip_length_km, class: 'control-label' %><br>
<div class="controls">
<%= f.number_field :transport_km %>
</div>
</div>
<div class="control-group">
<%= f.label :Number_of_trips, class: 'control-label' %><br>
<div class="controls">
<%= f.number_field :transport_num_of_trips %>
</div>
</div>
<div class="control-group">
<%= f.label :Recycled_fuel, class: 'control-label' %><br>
<div class="controls">
<%= f.number_field :transport_km_recycled_fuel %>
</div>
</div>
<div class="control-group">
<div class="controls">
<%= f.submit class: 'btn btn-xs btn-warning' %>
</div>
</div>
<% end %>
<%= link_to 'Back', transports_path %>
</div>
我还在 views/users/show.html.erb 中呈现此柱状图表,这是一个 Chartkicks 图表。
<div class="col-md-6 chart-box">
<%= column_chart [
{name: "CarTrips #{current_user.profile.name}", data: current_user.transports.group(:transport_type).sum(:transport_km)},
{name: "CarTrips Everyone Median", data: Transport.group(:transport_type).average(:transport_km)}], { stacked: true, height: "300px", xtitle: "CarTrips", ytitle: "Km/CarTrips"} %>
</div>
如您所见,无论他们从事何种业务,我都能显示每个用户的平均汽车行程。如何让 Current_user 只看到同一用户的平均汽车行程他们所在的业务类型???这有可能吗?
在users_controller.rb 我在show方法中有这个
def show
@user = User.find(params[:id])
@users = User.order('created_at DESC').paginate(page: params[:page], per_page: 30)
@transport = current_user.transports.build
end
添加模型
这是user.rb 模型
class User < ActiveRecord::Base
has_one :profile
accepts_nested_attributes_for :profile
def average_transport_types
self.transports.group(:transport_type).sum(:transport_km)
end
end
这是profile.rbmodel
class Profile < ActiveRecord::Base
belongs_to :user
end
【问题讨论】:
标签: ruby-on-rails ruby average chartkick