我正在尝试使用select标记在父级中保存多个嵌套子级。
这是我正在查看的错误
Couldn't find all UserLocations with IDs (1, 2) (found 0 results, but was looking for 2)
我在Rails 4
和Devise
下面进行了以下设置:
用户
class User < ActiveRecord::Base
has_many :user_locations
accepts_nested_attributes_for :user_locations, :allow_destroy => true
end
UserLocation (用户拥有的位置)
class UserLocation < ActiveRecord::Base
belongs_to :user
belongs_to :location
end
位置(用户可以选择的预定义位置列表)
class Location < ActiveRecord::Base
has_many :user_locations
has_many :users, through: :user_locations
end
但是,在尝试保存选定的UserLocations
时,系统不会保存这些内容。
Rails选择标记(您可以选择多个项目)
<%= f.select :user_location_ids, options_for_select(Location.all.collect { |l| [ l.name, l.id ] }, @user.user_locations.collect{ |l| l.id }), {}, { multiple: true } %>
我已将user_location_ids
放在application_controller
user_location_ids: []
干杯
答案 0 :(得分:0)
<强>解决强>
解决方案是覆盖多个嵌套模型model_ids=(value)
的默认setter方法。 不使用模型的复数形式,例如models_ids=(value)
,因为错误!
def user_location_ids=(value)
for slot in value do
unless slot == ""
location = Location.find_by(id: slot.to_i)
unless location.nil?
self.user_locations << UserLocation.create(user_id: self.id, location_id: location.id)
end
end
end
end