Anton
Anton

Reputation: 23

How to display photos by rating with Ruby on Rails framework?

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.

Upvotes: 1

Views: 194

Answers (1)

Georg Ledermann
Georg Ledermann

Reputation: 2752

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 %>

Upvotes: 1

Related Questions