使用 Accepts_nested_attributes_for + Rails 中的批量分配保护
假设您有以下结构:
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
请注意,电视的用户无法故意访问。 因此,您有一个三重嵌套表单,允许您在一页上输入房屋、房间和电视。
以下是控制器的创建方法:
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
不可批量分配
- 保存将失败,因为
- #save 完成后为每台电视填充用户
- 保存将失败,因为
user_id
必须存在 - 即使我们绕过上述内容,电视也会暂时没有 id - 糟糕
- 保存将失败,因为
什么好的方法可以做到这一点吗?
Say you have this structure:
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
Notice that Tv's user is not accessible on purpose. So you have a tripple-nested form that allows you to enter house, rooms, and tvs on one page.
Here's the controller's create method:
def create
@house = House.new(params[:house])
if @house.save
# ... standard stuff
else
# ... standard stuff
end
end
Question: How in the world would you populate user_id
for each tv (it should come from current_user.id)? What's the good practice?
Here's the catch22 I see in this.
- Populate
user_ids
directly intoparams
hash (they're pretty deeply nested)- Save will fail because
user_ids
are not mass-assignable
- Save will fail because
- Populate user for every tv after #save is finished
- Save will fail because
user_id
must be present - Even if we bypass the above, tvs will be without ids for a moment of time - sucks
- Save will fail because
Any decent way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这有什么问题吗?
我还没有尝试过这一点,但似乎此时应该构建对象并可以访问它们,即使没有保存。
Anything wrong with this?
I haven't tried this out, but it seems like the objects should be built and accessible at this point, even if not saved.