oobie11
oobie11

Reputation: 925

How do I submit a collection_check_box through the controller with a has_many through relationship?

Im on rails 4. I have three models, Blends, Addons and AddonPairings. Users create Blends and

Blend
  have_many :addon_pairings
  have_many :addons, through: :addon_pairings

Addon
  have_many :addon_pairings
  have_many :blends, through: :addon_pairings

AddonPairing
  belong_to :blend
  belong_to :addon

My addons are all premade in the db for users to choose as many as they want to attach to a blend.

In my new.html.erb for my blends

<%= form_for [current_user, @blend] do |f| %>

    <div class="form-group">
        <%= f.label :addons,  "Add some addons to your blend" %>
        <%= f.collection_check_boxes :addon_ids, Addon.all, :id, :name %>
    </div>

    <div class="form-group">
        <%= f.submit class: "btn btn-lg btn-primary" %>
    </div>
<% end %>

My Blend Controller

def create
    @user = User.find(params[:user_id])
    @blend = @user.blends.build(blend_params)
    if @blend.save
        redirect_to @user, notice: "Your blend has been created."
    else
        flash.now[:notice] = "Something went wrong. Please check the errors below."
        render 'new'
    end
  end
private

def blend_params
        params.require(:blend).permit(:name, :addon_ids)
    end

How do I make my controller create the records in my addon_pairings table that connect the blend to the addons chosen? Thanks.

Upvotes: 3

Views: 683

Answers (2)

Pwnrar
Pwnrar

Reputation: 1337

in your blend_params method just change

params.require(:blend).permit(:name, :addon_ids)

to

params.require(:blend).permit(:name, addon_ids: [])

Upvotes: 0

Hamdan
Hamdan

Reputation: 193

You have implemented it somekind badly.

Youll need to use 'accepts_nested_parameters' to do so.

This way, youll use fields_for tag to create a 'form in the form' that actually creates the fields in the other model making this entry owned by the current object that triggered the controller and generated the main form. So, since your collection_check_box create objects owned by the current one, but in another model, it needs to be inside a block like (just an example):

<%= fields_for @owner.belonged_name %>
<%= collection_check_box %>
<% end %>

I recommend you railscasts.com/episodes/196-nested-model-form-part-1 and this link (http://www.createdbypete.com/articles/working-with-nested-forms-and-a-many-to-many-association-in-rails-4/) to understand the philosphy about nested parameters.

Note that youll have to permit the attributes on your controller too since attr_params are deprecated.

Hope it helps.

Upvotes: 1

Related Questions