Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p><strong>Update:</strong></p> <p>I found a slightly more "magical" way to do this using <a href="http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html#method-i-accepts_nested_attributes_for" rel="nofollow noreferrer"><code>accepts_nested_attributes_for</code></a>. First, add a line to your <code>CauseUserMembership</code> model:</p> <pre><code>class CauseUserMembership &lt; ActiveRecord::Base attr_accessible :cause_id, :user_id belongs_to :user belongs_to :cause accepts_nested_attributes_for :cause </code></pre> <p>With that change, you can do this:</p> <pre><code>def create @membership = current_user.memberships.build @membership.cause = Cause.new(params[:cause].merge(:created_by =&gt; current_user.id) respond_to do |format| if @membership.save ... </code></pre> <p>Because you have told rails to accept nested attributes for the <code>cause</code> association on <code>CauseUserMembership</code>, it will save the new cause you assigned to <code>@membership.cause</code> when it saves the membership itself. So you can save both the cause and membership records at one time, rather than separately.</p> <p><strong>Original answer:</strong></p> <p>I think what you've done is pretty much the right way to do this. It can be simplified a tad bit: you don't need to build <code>cause</code> from <code>current_user</code>, you can just use <code>new</code> (the <code>:through</code> associations on <code>cause</code> and <code>current_user</code> are set when you create <code>@membership</code>).</p> <p>So like this (I only changed the first line in <code>create</code>):</p> <pre><code>def create @cause = Cause.new(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 ... </code></pre> <p>See also: <a href="https://stackoverflow.com/questions/9432343/many-to-many-through-association-build-create-properties-in-rails-app">Many-to-Many through association Build/Create properties in Rails app</a></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. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      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