Rails - 多个嵌套属性

时间:2014-02-27 17:50:51

标签: ruby-on-rails-4 devise nested-forms nested-attributes

我正在尝试使用select标记在父级中保存多个嵌套子级。

这是我正在查看的错误

Couldn't find all UserLocations with IDs (1, 2) (found 0 results, but was looking for 2)

我在Rails 4Devise下面进行了以下设置:

用户

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: []

干杯

1 个答案:

答案 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