Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>This can be done quite easily using accepts_nested_attributes_for and fields_for:</p> <p>First in the User model you do the following:</p> <pre><code>class User &lt; ActiveRecord::Base has_many :subscriptions accepts_nested_attributes_for :subscriptions, :reject_if =&gt; proc { |attributes| attributes['queue_id'].to_i.zero? } # if you hit scaling issues, optimized the following two methods # at the moment this code is suffering from the N+1 problem def subscription_for(queue) subscriptions.find_or_initialize_by_queue_id queue.id end def subscribed_to?(queue) subscriptions.find_by_queue_id queue.id end end </code></pre> <p>That will allow you to create and update child records using the subscriptions_attributes setter. For more details on the possibilities see <a href="http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html#M002132" rel="nofollow noreferrer">accepts_nested_attributes_for</a></p> <p>Now you need to set up the routes and controller to do the following:</p> <pre><code>map.resources :users do |user| user.resource :subscriptions # notice the singular resource end class SubscriptionsController &lt; ActionController::Base def edit @user = User.find params[:user_id] end def update @user = User.find params[:user_id] if @user.update_attributes(params[:user]) flash[:notice] = "updated subscriptions" redirect_to account_path else render :action =&gt; "edit" end end end </code></pre> <p>So far this is bog standard, the magic happens in the views and how you set up the params: app/views/subscriptions/edit.html.erb</p> <pre><code>&lt;% form_for @user, :url =&gt; user_subscription_path(@user), :method =&gt; :put do |f| %&gt; &lt;% for queue in @queues %&gt; &lt;% f.fields_for "subscriptions[]", @user.subscription_for(queue) do |sf| %&gt; &lt;div&gt; &lt;%= sf.check_box :queue_id, :value =&gt; queue.id, :checked =&gt; @user.subscribed_to?(queue) %&gt; &lt;%= queue.name %&gt; &lt;%= sf.text_field :random_other_data %&gt; &lt;/div&gt; &lt;% end %&gt; &lt;% end %&gt; &lt;% end %&gt; </code></pre>
    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