0

This example has been taken from Rails 4 Form: has_many through: checkboxes

models:

#models/user.rb
class User < ActiveRecord::Base
  has_many :animals, through: :animal_users
  has_many :animal_users
end

#models/animal.rb
class Animal < ActiveRecord::Base
  has_many :users, through: :animal_users
  has_many :animal_users
end

#models/animal_user.rb
class AnimalUser < ActiveRecord::Base
  belongs_to :animal
  belongs_to :user
end

The user form:

#views/users/_form.html.erb
<%= form_for(@user) do |f| %>
  <div class="field">
    <%= f.label :name %><br>
    <%= f.text_field :name %>
  </div>

  # Checkbox part of the form that now works!
    <div>
      <% Animal.all.each do |animal| %>
        <%= check_box_tag "user[animal_ids][]", animal.id, f.object.animals.include?(animal) %>
        <%= animal.animal_name %>
      <% end %>
    </div>

  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

Strong params within the users_controller.rb

 def user_params
    params.require(:user).permit(:name, animal_ids: [])
  end

I followed this example and could not save the join table. I have two question here

  1. What type should be animal_ids, string or integer?
  2. How to save the form?

Currently I am saving it like this

def create

    respond_to do |format|
      if @user.save
        format.html { redirect_to @user, notice: 'user was successfully created.' }
        format.json { render json: @user, status: :created, location: @user}
      else
        format.html { render action: "new" }
        format.json { render json: @user.errors, status: :unprocessable_entity }
      end
    end
  end

And this only create user but not the join table. How can I do this?

Community
  • 1
  • 1
  • animal_ids will array of integer. Secondly where you have written intialization of `@user`. `@user = User.new(user_params)` – Pardeep Dhingra Nov 17 '15 at 14:02
  • Where is the `@user` defined in the `create` action? – Pavan Nov 17 '15 at 14:02
  • I don't have this initialization and still creating users. I think in rails4 it doesn't matter. @user = User.new(user_params). Do I have to add a column in user table for animal_ids? –  Nov 17 '15 at 14:05

1 Answers1

0

@user.save is not passing in the nested attributes (animal_ids)

You'll need to pass the params like this:

@user = User.new(user_params)

And in your User model (user.rb) you need to add something like:

accepts_nested_attributes_for :animals
accepts_nested_attributes_for :animal_users
Jeff F.
  • 1,039
  • 5
  • 11