假设您有这种结构:
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
请注意,Tv的用户无法故意访问。所以你有一个三层嵌套的表格,允许你在一个页面上输入房子,房间和电视。
这是控制器的创建方法:
def create
@house = House.new(params[:house])
if @house.save
# ... standard stuff
else
# ... standard stuff
end
end
问题:世界上你如何为每部电视填充user_id
(它应该来自current_user.id)?什么是好的做法?
这是我在此看到的catch22。
user_ids
直接填充到params
哈希(它们非常嵌套)
user_ids
不可批量分配user_id
必须存在有什么好办法吗?
答案 0 :(得分: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
我没有试过这个,但似乎这个对象应该在这时构建和访问,即使没有保存。