3

I have three Models. Both makes and models table have name column inside.

class Review < ActiveRecord::Base
    belongs_to :model
end

class Model < ActiveRecord::Base
    belongs_to :make
    has_many :reviews
end

class Make < ActiveRecord::Base
    has_many :models
end 

In Active Admin on Index Page I want to sort reviews by make and model. I figured out how to sort it by model, because it has key the reviews table. Tried a lot of things. Nothing works to sort by make name. I was able to list though.

ActiveAdmin.register Review do
    column "Model", sortable: 'model_id' do |p|
        p.model.name
    end
    column "Make", sortable: 'make_id' do |review|
        review.model.make.name
    end
end

Only sorting by model name works. I think if I add make_id to Reviews it will be working, but it seems redundant, cause a chain like review.model.make perfectly works

4

1 回答 1

0

假设 areview是 1 到 5 之间的分数。您必须计算每个 的平均值 make

要计算 a 的平均值make,请执行以下操作:

reviews_sum = 0
total_reviews = 0

make.models.each do |model|
  model.reviews.each do |review|
    reviews_sum += review
    total_reviews += 1
  end
end

然后:

average_review = reviews_sum /  total_reviews.to_f # I am using to_f to convert total_reviews from integer to float. This way you can have a float result.

我建议你创建一个make_average_review(make_id, average_review) 这样你可以存储/更新你的平均评论make,然后排序make

于 2015-08-14T01:59:50.153 回答