views:

60

answers:

1

Ok. I've got a model Picture

class Picture < ActiveRecord::Base
  has_one  :rating
  has_many :comments
end

And, of course Rating model

class Rating < ActiveRecord::Base
  belongs_to :picture
end

I made rating system by myself. So, now on the frontpage I need to display all photos by rating. Please, can u show me how to do that. I've no idea what will be in index.html.erb of main controller.

A: 

If Rating has an integer field "value", you can do this:

class Picture < ActiveRecord::Base
  has_one  :rating

  named_scope :by_rating, { :joins => :rating, :order => 'ratings.value DESC' }
end

Now, in the controller you can use this:

@pictures_top10 = Picture.by_rating.all :limit => 10

In the view:

<% @pictures_top10.each do |picture| %>
  <%= image_tag(picture.url) %>
<% end %>
Georg Ledermann
Tnanks, but i need to get fields from table Ratings in result!
Anton
Including Rating columns is possible, too: named_scope :by_rating, { :joins => :rating, :order => 'ratings.value DESC', :select => 'pictures.*, ratings.*' }
Georg Ledermann