Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do I set up to has_many/belongs_to assocations so that only one combination is allowed?
    primarykey
    data
    text
    <p>I have three tables, applicants, users and ratings. The basic idea is that each applicant gets assigned a rating by any number of users. This part I have working without any problems. However, if a user goes to edit their rating (which includes a score), the form adds a second rating. I need to change things so that each user can only assign one rating for a given applicant.</p> <pre><code>class Applicant &lt; ActiveRecord::Base has_many :ratings accepts_nested_attributes_for :ratings, :allow_destroy =&gt; true class User &lt; ActiveRecord::Base has_many :ratings </code></pre> <p>The rating table just contains an applicant_id, a user_id and a score.</p> <pre><code>class Rating &lt; ActiveRecord::Base belongs_to :user belongs_to :applicant validates_uniqueness_of :applicant_id, :scope =&gt; :user_id </code></pre> <p>The rating validation makes sure that a second rating is not accepted, but I need to change the associations (or the form) so that a second score option never appears.</p> <p>My applicant form:</p> <pre><code>&lt;%= f.fields_for :ratings do |builder| %&gt; &lt;%= builder.collection_select :score, Rating::SCORES, :to_s, :humanize %&gt; &lt;%= builder.hidden_field :user_id, :value =&gt; current_user.id %&gt; &lt;%= builder.hidden_field :applicant_id, :value =&gt; @applicant.id %&gt; &lt;% end %&gt; </code></pre> <p>How do I specify (in the applicant model, I'd guess, since that's the form I'm editing) that the applicant_id, user_id combo in the ratings table has to be unique?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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