如何在 Rails 中构建一次父母的孩子

发布于 2024-10-06 02:52:44 字数 546 浏览 3 评论 0原文

如何确保父级仅在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

番薯 2024-10-13 02:52:44
if ( session[:members_built] == false )
  @membership.build_members
  session[:members_built] = true
end

我建议您不要使用这样的代码。这违背了 MVC 原则。因此将其移至控制器中。另请查看Rails 关联指南

所以你可以

@membership.build_members

在你的控制器中做类似的事情。您不必使用会话变量来记住是否调用了 #build_members,因为使用 #build 不会保存对象。因此,当用户刷新页面时,控制器将再次调用#build_members,您的视图应该是您想要的。

if ( session[:members_built] == false )
  @membership.build_members
  session[:members_built] = true
end

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

@membership.build_members

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文