开发者

How to Build a Parent's Children Only Once in Rails

开发者 https://www.devze.com 2023-01-29 05:48 出处:网络
How can I ensure that a Parent only builds its Children n times in Rails? Is there a way to find non-persisted instances?

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 =&开发者_C百科gt; { :ff => ff } %>

In the model:

  def build_members
    (membership_type.adults - 1).times {members.build}
  end


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消