【发布时间】:2016-02-18 22:24:53
【问题描述】:
这个例子取自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
我按照此示例进行操作,但无法保存连接表。我这里有两个问题
- animal_ids、字符串还是整数应该是什么类型?
- 如何保存表单?
目前我是这样保存的
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
这只会创建用户而不是连接表。我该怎么做?
【问题讨论】:
-
animal_ids 将是整数数组。其次,您已经编写了
@user的初始化。@user = User.new(user_params) -
@user在create操作中定义在哪里? -
我没有这个初始化并且还在创建用户。我认为在rails4中没关系。 @user = User.new(user_params)。我必须在用户表中为 animal_ids 添加一列吗?
标签: ruby-on-rails ruby-on-rails-4