Reputation: 126
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
Upvotes: 3
Views: 347
Reputation: 1000
Let's say a review
is a score between 1 and 5.
You will have to compute the average value for each make
.
To compute an average value for a make
, do:
reviews_sum = 0
total_reviews = 0
make.models.each do |model|
model.reviews.each do |review|
reviews_sum += review
total_reviews += 1
end
end
Then:
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.
I advice you to create an make_average_review(make_id, average_review)
This way you can store/update your average review for every make
and then sort by make
Upvotes: 0