我想创建属性。然后将其添加到许多列表中。一个属性可以列在许多列表中。
这是我的模特:
class List < ActiveRecord::Base
has_many :propertyships
has_many :properties, :through => :propertyships
end
class Propertyship < ActiveRecord::Base
belongs_to :list
belongs_to :property
end
class Property < ActiveRecord::Base
has_many :propertyships
has_many :lists, :through => :propertyships
end
属性/ show.html.erb
<%= form_for @property do |f| %>
<% List.all.each do |list| %>
<%= check_box_tag "property[list_ids][]", list.id,@property.list_ids.include?(list.id) %>
<%= list.name %>
<% end %>
<%= f.submit %>
<% end %>
属性不会添加到列表中。 我做错了什么?
答案 0 :(得分:3)
使用collection_check_boxes
代替手动创建输入:
<%= form_for @property do |f| %>
<%= f.collection_check_boxes(:list_ids, List.all, :id, :name) %>
<%= f.submit %>
<% end %>
将params列入白名单有点特殊,因为params[:property][:list_ids]
将包含一个数组:
class PropertiesController < ApplicationController
# ...
def create
@property = Property.new(property_params)
# ...
end
# ...
private
def property_params
params.require(:property)
.permit(:foo, :bar, list_ids: [])
end
end