在Rails中使用accepts_nested_attributes_for +质量分配保护

Max*_*yak 6 ruby ruby-on-rails nested-forms mass-assignment

假设你有这个结构:

class House < ActiveRecord::Base
  has_many :rooms
  accepts_nested_attributes_for :rooms
  attr_accessible :rooms_attributes
end

class Room < ActiveRecord::Base 
  has_one :tv
  accepts_nested_attributes_for :tv
  attr_accessible :tv_attributes
end

class Tv 
  belongs_to :user
  attr_accessible :manufacturer
  validates_presence_of :user
end
Run Code Online (Sandbox Code Playgroud)

请注意,Tv的用户无法故意访问.所以你有一个三层嵌套的表格,允许你在一个页面上输入房子,房间和电视.

这是控制器的创建方法:

def create
  @house = House.new(params[:house])

  if @house.save
    # ... standard stuff
  else
    # ... standard stuff
  end
end
Run Code Online (Sandbox Code Playgroud)

问题:你将如何填充user_id每个电视(它应该来自current_user.id)?什么是好的做法?

这是我在这看到的catch22.

  1. user_ids直接填充params哈希(它们非常嵌套)
    • 保存将失败,因为user_ids不可批量分配
  2. 在#save完成后为每个电视填充用户
    • 保存将失败,因为user_id必须存在
    • 即使我们绕过上述情况,电视也会暂时没有ids - 很糟糕

有任何体面的方式吗?

Mat*_*orn 2

这有什么问题吗?

def create
  @house = House.new(params[:house])
  @house.rooms.map {|room| room.tv }.each {|tv| tv.user = current_user }
  if @house.save
    # ... standard stuff
  else
    # ... standard stuff
  end
end
Run Code Online (Sandbox Code Playgroud)

我还没有尝试过这一点,但似乎此时应该构建对象并可以访问它们,即使没有保存。