我正在学习教程并有模型user
,hotel
并且rating
. 用户可以创建酒店,用户可以对其进行评分。用户评分值与和rating
一起记录到表中。当我渲染部分时,它显示了在模型Model Hotel.rb中计算的平均评级的酒店列表:user_id
hotel_id
<%= render "hotels/hotels_list", :@hotels => Hotel.all %>
hotel
class Hotel < ActiveRecord::Base
attr_accessible :user_id
belongs_to :user
has_many :ratings
has_many :raters, :through => :ratings, :source => :users
def average_rating
@value = 0
self.ratings.each do |rating|
@value = @value + rating.value
end
@total = self.ratings.size
'%.2f' % (@value.to_f / @total.to_f)
end
end
模型用户.rb:
class User < ActiveRecord::Base
has_many :hotels
has_many :ratings
has_many :rated_hotels, :through => :ratings, :source => :hotels
end
模型评级.rb:
class Rating < ActiveRecord::Base
attr_accessible :value
belongs_to :user
belongs_to :hotel
end
我需要按平均评分对酒店列表进行排序,可能需要添加一些列 ,以便像酒店模型中的average_rating
该方法一样立即计算平均值average_rating
,这样我就可以轻松访问它。我该如何解决这个问题?
RatingsController.rb
class RatingsController < ApplicationController
before_filter :authenticate_user!
def create
@hotel = Hotel.find_by_id(params[:hotel_id])
@rating = Rating.new(params[:rating])
@rating.hotel_id = @hotel.id
@rating.user_id = current_user.id
if @rating.save
respond_to do |format|
format.html { redirect_to hotel_path(@hotel), :notice => "Your rating has been saved" }
format.js
end
end
end
def update
@hotel = Hotel.find_by_id(params[:hotel_id])
@rating = current_user.ratings.find_by_hotel_id(@hotel.id)
if @rating.update_attributes(params[:rating])
respond_to do |format|
format.html { redirect_to hotel_path(@hotel), :notice => "Your rating has been updated" }
format.js
end
end
end
end