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?
The problem is that the instance variable
@it_shouldwhich you set with theattr_accessoris not persisted between requests, so although you set it totruein yournewaction, it will be reset as soon as the form is submitted and some other action (probablycreateorupdate) 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:This should trigger the validation on
nameas expected.