使用simple_form构建具有多个关联输入的双嵌套表单

时间:2015-03-20 10:36:53

标签: ruby-on-rails associations simple-form multipleselection

如果之前有人问我,请指点我。我找不到它。 在这个应用程序中,我将选择多个团队的一些用户,他们应该收到某些请求。所以我得到了以下模型:

class Request < ActiveRecord::Base
  has_many :request_teams
  has_many :teams, through: :request_teams
  belongs_to :club
  belongs_to :requester, class_name: User, foreign_key: :requester_id
end

class RequestTeam < ActiveRecord::Base
  belongs_to :request
  belongs_to :team
  has_many :request_coaches
  has_many :coaches, through: :request_coaches
end

class RequestCoach < ActiveRecord::Base
  belongs_to :request_team
  belongs_to :coach, class_name: User
end

我的方法是首先选择团队并提交他们,然后为应该收到请求的团队选择教练。第一步很好地适用于:

= simple_form_for @request do |f|
  = f.association :teams, as: :check_boxes, collection: @teams

但我无法完成下一步的工作。

= simple_form_for @request do |f|
  - for request_team in @request.request_teams
    = f.simple_fields_for :request_teams, request_team do |ft|
      = request_team.team.name
      = ft.input :coaches, as: :select, collection: request_team.team.coaches, input_html: { multiple: 'multiple' }

似乎问题在于它在params中聚合了一个数组中的所有教练,而不是将它们绑定到适当的request_team。收到的参数类似于:"request"=>{"request_teams"=>{"coaches"=>["57","136371"]}}

当我查看呈现的HTML时,表单输入名称如下所示:

name="request[request_teams][coaches][]"

我希望它看起来更像:

name="request[request_teams][some_request_team_id_here][coaches][]"

这可能吗?我做错了什么?

1 个答案:

答案 0 :(得分:-1)

这确实是可能的。我只是忘了在accepts_nested_attributes_for。