如何在 Rails 中构建一次父母的孩子
如何确保父级仅在 Rails 中构建其子级 n 次?
有没有办法找到非持久实例?
我目前遇到一个问题,我在第一次加载页面时创建子级。当用户刷新页面时,子级不会被加载,因为它们已经被创建,但尚未被持久化。
关于如何解决这个问题有什么想法吗?
在视图中:
if ( session[:members_built] == false )
@membership.build_members
session[:members_built] = true
end
...
<% f.fields_for :members do |ff| %>
<%= render :partial => "member", :locals => { :ff => ff } %>
在模型中:
def build_members
(membership_type.adults - 1).times {members.build}
end
How can I ensure that a Parent only builds its Children n times in Rails?
Is there a way to find non-persisted instances?
I'm currently having a problem where I create the children on the first load of a page. When a user refreshes the page, the children are not loaded because they have already been created, but have not been persisted.
Any ideas on how to solve this problem?
In the view:
if ( session[:members_built] == false )
@membership.build_members
session[:members_built] = true
end
...
<% f.fields_for :members do |ff| %>
<%= render :partial => "member", :locals => { :ff => ff } %>
In the model:
def build_members
(membership_type.adults - 1).times {members.build}
end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我建议您不要使用这样的代码。这违背了 MVC 原则。因此将其移至控制器中。另请查看Rails 关联指南。
所以你可以
在你的控制器中做类似的事情。您不必使用会话变量来记住是否调用了 #build_members,因为使用 #build 不会保存对象。因此,当用户刷新页面时,控制器将再次调用#build_members,您的视图应该是您想要的。
I would recommend not having code like this is your views. It's going against MVC principles. So move it into the controller. Also checkout the Rails Guides for associations.
So you could do something like
in your controller. You don't have to use a session variable to remember if you called #build_members because using #build doesn't save the object. So when a user refreshes the page, the controller will call #build_members again and your view should be what you want.