views:

34

answers:

2

I am implementing a multi-model form and it is carried across multiple pages. I have a method to try and ensure that the nested model only gets generated once:

  def initialize(*params)
    super(*params)

    if (@new_record)
      @main_generated = false
    end
  end 

  def generate_main
    if !@main_generated
      members.build(:main => true, :firstname => "Hello World")
      @main_generated = true
    end
  end

The problem is that it appears that my main_generated variable is not accessible. How come? Is there a way to check if, for example, @account.members contained a member that was built but not saved?

+1  A: 

If what you've given is your actual code, then @main_generated is declared in a class scope, which makes it a class variable inaccessible to an instance of the class. You need to initialize @main_generated in the context of an instance method, for example:

EDIT: lol, MEHColeman makes an excellent point. "false" should be false.

def initialize
  @main_generated = false # or whatever your default value would be...
end

In answer to your second question:

Is there a way to check if, for example, @account.members contained a member that was built but not saved?

You could try something like:

@account.members.any? {|member| member.new_record?}

Or to actually return any non-persisted objects:

@account.members.select {|member| member.new_record?}
Dave Sims
Updated question above considering your answer but unfortunately the problem still persists
aaronmase
+1  A: 

FWIW, the string "false" evaluates to true in ruby.

The only values that evaluate to false are nil and false. Even 0 evaluates to true!

MEHColeman
very good point!
aaronmase