Note that there are some explanatory texts on larger screens.

plurals
  1. PORails 3: Has_many through and Me
    text
    copied!<p>I'm fairly new to Rails, I got this code working but I think I'm preventing it from doing it some of its Rails magic:</p> <p><strong>Goal</strong>: Create a <code>cause</code> and have the creator become a member via the <code>build</code> method and the <code>has_many :through</code> association in the <code>Cause_User_Membership</code> table. </p> <p><strong>Question</strong>: I've gotten it to work, by creating a <code>cause</code> and then creating a membership 'manually.' Is there a way for the <code>Cause_User_Membership</code> relationship to be created automatically on the creation of a <code>cause</code>?</p> <p><strong>Cause_Controller.rb</strong></p> <pre><code>def create @cause = current_user.causes.build(params[:cause].merge :created_by =&gt; current_user.id) respond_to do |format| if @cause.save @membership = current_user.cause_user_memberships.build(:cause_id =&gt; @cause.id) @membership.save format.json { render :json =&gt; {current_user: current_user, results: @cause}} else format.json { render :json =&gt; {Message: "You messed up"}} end end end </code></pre> <p><strong>User.rb (snippet)</strong></p> <pre><code>has_many :cause_user_memberships has_many :causes, :through =&gt; :cause_user_memberships </code></pre> <p><strong>Cause.rb</strong></p> <pre><code>attr_accessible :title, :location, :description,... has_many :cause_user_memberships has_many :users, :through =&gt; :cause_user_memberships </code></pre> <p><strong>Cause_User_Membership.rb</strong> (&lt;--probably not my best model name)</p> <pre><code> # == Schema Information # # Table name: cause_user_memberships # # id :integer not null, primary key # user_id :integer not null # cause_id :integer not null # created_at :datetime not null # updated_at :datetime not null # class CauseUserMembership &lt; ActiveRecord::Base attr_accessible :cause_id, :user_id belongs_to :user #, :class_name =&gt; "User", :foreign_key =&gt; "user_id" belongs_to :cause #, :class_name =&gt; "Cause", :foreign_key =&gt; "cause_id" end </code></pre>
 

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