如何将has_many关系与选择一起使用



给定ProblemObserver模型:

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 => []}]})创建规则,它也会产生错误的关系,只有problem_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)

按照你这样做的方式,你说你只需要一个具有多个user_ids的观察者,事实上你想要的是每个用户(和问题)一个观察者。

您可能应该使用如下关联模型:http://guides.rubyonrails.org/association_basics.html#the-has-and-belongs-to-many-association

请记住按字母顺序创建关联,在您的案例模型中,问题用户和表problems_users。

然后,您可以像这里一样填写表格:https://stackoverflow.com/a/9917006/1217298 – 请阅读问题和答案以更好地理解。

希望对您有所帮助。

最新更新