I have a Person model. When a new Person is created, I want to set a random_variable in the controller and pass it as part of the @person object. I have tried
Model
attr_accessor :random_variable
Controller:
def create
@person = Person.new(params[:person])
@person.random_variable = 'A Random string'
@person.save
end
Unfortunately, if I try and access self.random_variable in the model, this doesn't work (I get nil).
Can someone explain why this doesn't work, and how to go about doing it? (and yes, I know this doesn't really hold with MVC convention, but the only other way of doing what I need开发者_如何转开发 is a very heavy non-dry controller)
What you are describing should work. How are you determining that the random variable is in fact nil? Have you tried using the debugger?
Have you tried just using update_attribute?
update_attribute(:random_variable, 'A Random string')
Or, maybe jump into script/console to see exactly what's happening.
Something weird is going on. I should have explained, as Brad suggested, that I am trying to access random_variable inside a setter method for another object. I had understood that params was handed to the controller, than the model only accessed once @person.save was called. For some reason the setter seems to be being hit before the controller.
I am basing this on the fact that when I accidentally put a debugger statement in the model setter method and controller at the same time, the model debugger was triggered first. I am clearly going to have to do some reading unless someone can explain this. Unfortunately I need to get this working tonight, so I will be going for a hack workaround for the time being
精彩评论