我正在构建一个RailsApp,用户可以在views/profiles/_form.html.erb
中通过f.select
声明他们的:buisness_type
。
然后在views/users/show.html.erb
中,current_user
可以在input_field中输入汽车旅行的值。
我想要能够做的是让current_user根据他们的:business_type过滤掉其他用户。因此,current_user可以在views/users/show.html.erb
中看到相同:business_type
中其他用户car_trip的平均值。
在views/profiles/_form.html.erb
中,我有以下代码保存在Profile.rb
模型中:
<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
中渲染这个列图。这是一个图表。
<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
<<p> 添加模型/strong> 这是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.rb
模型
class Profile < ActiveRecord::Base
belongs_to :user
end
只需将where
添加到拉出用户的部分上,例如:
@users = User.where(:business_type => current_user.business_type).order('created_at DESC').paginate(page: params[:page], per_page: 30)