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
- What type should be animal_ids, string or integer?
- 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?