Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy does this Rails association shortcut fail? What is the correct way?
    text
    copied!<p>In the given case a User may:</p> <ul> <li><strong>invite many invitees</strong> (has_many :invitations)</li> <li><strong>accept one invitation</strong> (has_one :invitation)</li> </ul> <p>According to <a href="http://guides.rubyonrails.org/association_basics.html#the-has_many-through-association" rel="nofollow">http://guides.rubyonrails.org/association_basics.html#the-has_many-through-association</a> a <strong>has_many :through</strong> association should allow me to use a shortcut like the one in the following functional test.</p> <p>However, it fails with the error noted in the comment.</p> <p><strong>snippet from functional test:</strong></p> <pre><code>assert_difference('Invitation.count') do # WORKS post :create, :user =&gt; { :email =&gt; invitee_email, :password =&gt; "1password" } end @invitee = User.find_by_email(invitee_email) @invitation = Invitation.find_by_issuer_id_and_invitee_id(@issuer.id, @invitee.id) assert @invitation.valid? # WORKS assert_present @invitation.issuer # WORKS assert_present @invitation.invitee # WORKS # TODO: repair assert_present @issuer.invitees # FAILS with "[] is blank" assert_present @invitee.issuer # FAILS with "nil is blank" </code></pre> <p><strong>snippet from the method under test:</strong></p> <pre><code>@issuer.create_invitation(:invitee =&gt; @invitee, :accepted_at =&gt; Time.now) # tested as well - also fails the test: # Invitation.create!(:issuer =&gt; @issuer, :invitee =&gt; @invitee, :accepted_at =&gt; Time.now) </code></pre> <p><strong>relevant parts of invitation.rb:</strong></p> <pre><code>belongs_to :issuer, :class_name =&gt; "User" belongs_to :invitee, :class_name =&gt; "User" validates_presence_of :issuer validates_presence_of :invitee </code></pre> <p><strong>relevant parts of user.rb:</strong></p> <pre><code>has_many :invitations, :foreign_key =&gt; 'invitee_id', :dependent =&gt; :destroy has_many :invitees, :through =&gt; :invitations has_one :invitation, :foreign_key =&gt; 'issuer_id', :dependent =&gt; :destroy has_one :issuer, :through =&gt; :invitation </code></pre> <p>Now I wonder:</p> <ul> <li><strong>What is the correct 'shortcut'?</strong></li> <li><strong>Are my models set up correctly in the first place?</strong></li> </ul>
 

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