In my konkurrancerstable I have:
rating_score => The current score (integer)
ratings => The number of ratings which led to the score (integer)
In my view I want to sort konkurrancers after rating. So I have to do this math: rating_score/ratings ratings may not be null because I can not divide be zero.
<% @konkurrencer.find(:all, :order => '@rating ASC', :limit => 5).each do |vind| %>
<%= link_to(image_tag(vind.banner2, :style => 'border:none; width:125px; height:125px;'), vind.tracking, :target => '_blank') %>
<% end %>
My controller:
class PublicController < ApplicationController
helper_method :sort_column, :sort_direction
def index
@konkurrencer = Konkurrancer
end
end
My view:
15: <%= @konkurrencer.find(:all, :select => "rating_score/ratings AS rating", :order => 'rating ASC', :limit => 5).each do |da| %>
16: <%= da.banner2 %>
17: <% end %>
And I get following error:
ActiveModel::MissingAttributeError in Public#index Showing C:/Rails/konkurranceportalen/app/views/public/_konkurrencer.html.erb where line #16 raised: missing attribute: 开发者_JS百科banner2
How do I create the instance variable rating to order the konkurrancers?
If nothing else, you can sort your list of records by two criteria after retrieving them from the database.
In the index
method in your controller, I'd do this:
@konkurrancers = Konkurrancer.find(:all, :order => '@rating ASC')
@konkurrancers.sort! {|a, b|
rel = a.rating_score <=> b.rating_score
# if "rating_scores" are equivalent, only then consider "ratings"
rel == 0 ? a.ratings <=> b.ratings : rel
}
That much will give you a list of all your Konkurrencer objects, sorted by two criteria.
In your view, I'd do this:
<% @konkurrancers[0,5].each do |vind| %>
<%= link_to(image_tag(vind.banner2, :style => 'border:none; width:125px; height:125px;'), vind.tracking, :target => '_blank') %>
<% end %
That should create the html for only the first 5 items in the list you made in your controller. (Is that what you wanted?)
If you are using SQL you can use
@konkurrencer.find(:all, :select => "rating_score/ratings AS rating", :order => 'rating ASC', :limit => 5)
class Konkurrencer
def rating
self[:rating] || (rating_score/rating)
end
end
rshallit linked to a good post about this above. However it is in Rails 3 and it appears you are using Rails < 3
精彩评论