Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I would use Polymorphic association:</p> <pre><code># file: app/models/item.rb class Item &lt; ActiveRecord::Base has_many :ratings, :as =&gt; :rateable end # file: app/models/user.rb class User &lt; ActiveRecord::Base has_many :ratings has_many :rated_items, :through =&gt; :ratings, :source =&gt; :rateable, :source_type =&gt; "Item" end # file: app/models/rating.rb class Rating &lt; ActiveRecord::Base belongs_to :user belongs_to :rateable, :polymorphic =&gt; true validates_uniqueness_of :user_id, :scope =&gt; :rateable end </code></pre> <p>With this your User can rate different Items, but only once per Item. </p> <p>To implement this you'd need <code>rateable_id</code> and <code>rateable_type</code> fields in your <code>ratings</code> table. Plus, off course, <code>user_id</code> and <code>rating_score</code> or something.</p> <p>The great advantage is that you are able to add as much <code>rateables</code> as you wish. If, for example, you want to rate a <code>Song</code> model, then you can simply implement it like this:</p> <pre><code># file: app/models/song.rb class Song &lt; ActiveRecord::Base has_many :ratings, :as =&gt; :rateable end </code></pre> <p>To show ratings for an <code>Item</code>: <code>item.ratings</code> To show all items rated by a <code>User</code>: <code>user.rated_items</code></p> <p>P.S. I am not good in English grammar, so correct me if have misspelled <code>rateable</code><br> P.P.S. this implementation is untested, I wrote it straight out of my head, so there's no guarantee it will work 100% :)</p> <p>Good luck!</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload