Rails 4:复选框和has_many通过

时间:2015-11-17 13:58:05

标签: ruby-on-rails ruby-on-rails-4

此示例取自Rails 4 Form: has_many through: checkboxes

模型:

#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

用户表单

#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 %>

users_controller.rb中的强参数

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

我按照此示例操作,无法保存连接表。我在这里有两个问题

  1. 什么类型应该是animal_ids,字符串或整数?
  2. 如何保存表单?
  3. 目前我正在保存它

    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
    

    这只创建用户而不是连接表。我怎么能这样做?

1 个答案:

答案 0 :(得分:0)

@ user.save没有传入嵌套属性(animal_ids)

你需要传递这样的参数:

@user = User.new(user_params)

在您的用户模型(user.rb)中,您需要添加以下内容:

accepts_nested_attributes_for :animals
accepts_nested_attributes_for :animal_users