给定Problem
和Observer
模型:
class Problem < ActiveRecord::Base
has_many :observers
accepts_nested_attributes_for :observers
end
class Observer < ActiveRecord::Base
belongs_to :problem
belongs_to :user
end
我试图用来form_for
选择用户作为观察者:
<%= f.fields_for :observers do |obs| %>
<%= obs.collection_select(:user_id, Users.to_a, :id, :name, {:include_blank => true, include_hidden: false}, {:multiple => true}) %>
<% end %>
但是 Rails 为 select: 生成了错误的名称problem[observers_attributes][0][user_id][]
,因此即使为 strong_params ( {:observers_attributes => [{:user_id => []}]}
) 创建规则也会创建错误的关系,只有 issue_id 进入数据库,并且所有 user_id 都被忽略。
我要做的是在多选中显示所有用户,获取 ID 并在Problem#new
方法中为他们创建关联。
更新 12.10
发布参数:
参数:{"utf8"=>"✓", "authenticity_token"=>"NHDl/hrrFgATQOoz9A3OLbLDAbTMziKMQW9X1y2E8Ek=", "problem"=>{"problem_data_attributes"=>{"title"=>"safasfasfafsasf", "description"=>""}, "observers_attributes"=>{"0"=>{"user_id"=>["5", "8"]}}}}
强参数:
def problem_params
params.require(:problem).permit({:files_attributes => [:attach_id]}, {:observers_attributes => {:user_id => []}}, {:problem_data_attributes => [:title, :description]})
end
创建方法
def create
@problem = @project.problem.build(problem_params)
@problem.account = current_account
if @problem.save
render :json => {status: true, id: @problem.id}
else
respond_with(@problem)
end
end
以及在创建调用期间创建观察者的 SQL:
SQL (0.2ms) INSERT INTO `observers` (`problem_id`) VALUES (96)