Question

I've always had consistency problems with attr_accessor in rails. I've never figured out what detail I am missing...so, I thought I would put a question here.

I have the following:

  ...Controller
  new
     @something = Something.new
     @something.it_should = true
  end

.

  ....Model
  attr_accessor :it_should

  def should_validate?
     it_should
  end

  validates_presence_of :name, :if => :should_validate?

So, I set the instance variable in the controller to true. I make that variable available to the model via attr_accessor. I put the variable into a method, then I use that method in the validation. Seems like it should work. But, it does nothing. it_should is never set to true. The the page loads fine, but field is not validated.

I even tried this...but, it didn't cause the validation to execute.

  def should_validate?
     true
  end

What are the tricks for using att_accessor?

Was it helpful?

Solution

The problem is that the instance variable @it_should which you set with the attr_accessor is not persisted between requests, so although you set it to true in your new action, it will be reset as soon as the form is submitted and some other action (probably create or update) is triggered.

If you want to validate a field this way, you'd have to set it in the action triggered by the form submission, e.g. create:

def create
  @something = Something.new(params[:something])
  @something.it_should = true
  @something.save
  ...
end

This should trigger the validation on name as expected.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top