我的目标是通过集合选择字段通过Viewer
在Search
模型和ExlcudingViewers
模型之间添加多对多关系。提交表单时,实际上没有创建任何关系。那是为什么?
搜索模型:
class Search < ActiveRecord::Base
has_many :viewers, through: :excluding_viewers
has_many :excluding_viewers
...
def excluding_viewers_list
viewers.map(&:id)
end
def excluding_viewers_list=(ids)
self.viewers.clear
ids.each do |id|
viewer = Viewer.find(id)
self.viewers << viewer if viewer
end
end
...
end
观众模型:
class Viewer < ActiveRecord::Base
has_many :excluding_viewers
has_many :searches, through: :excluding_viewers
end
ExcludingViewer模型:
class ExcludingViewer < ActiveRecord::Base
belongs_to :viewer
belongs_to :search
end
我用于搜索的表单:
<%= form_for @search do |f| %>
...
<%= f.collection_select :excluding_viewers_list,
Viewer.order(:name),
:id,
:name,
{},
multiple: true,
class: "chosen-select" %>
<%= f.submit "Search", class: "btn btn-primary search-cntrls" %>
<% end %>
控制器工作正常,当我从表单发布信息时,:excluding_viewers_list
数据格式为["", "1", "3"]
,如果我选择ID为1和3的查看器