Rails how to differentiate two columns in controller?
My association are described below:
Konkurrancers belongs to Kategori
Kategori has many Konkurrancers.
In my konkurrancers table i have:
rating_score
ratings
class KategorisController < ApplicationController
def show
@kategori = Kategori.where(:cached_slug => params[:id]).first
// Does not work
@rating = @kate开发者_如何学Pythongori.konkurrancers.rating_score / @kategori.konkurrancers.ratings
end
end
I get this error in view:
NoMethodError in KategorisController#show
undefined method `rating_score' for #<Class:0x5f3e590>
The column ratings holds the number of ratings and the rating_score holds the rating
And I want to differentiate those two columns as following: rating_score/ratings
How do I create this in my controller?
Since kategori
has multiple konkurrancers
so konkurrancers is an array. You need to define of which konkurrancers you take the rating_score
You should try:
@kategori.konkurrancers[0].rating_score
Above code will only work if you have at least 1 @kategori.konkurrancers
ofcourse
UPDATE
@rating = 0
@kategori.konkurrancers.each do |k|
@rating += k.rating_score
end
@rating /= @kategori.konkurrancers.count
精彩评论