views:

54

answers:

3

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)

A: 

What you are describing should work. How are you determining that the random variable is in fact nil? Have you tried using the debugger?

Beerlington
sparky
As I said, your code should work. The only other thing I can think of is that you are trying to access random_variable at a different point in time and assuming it is a persistent property of Person. It will only be available as long as the `@person` instance is in scope.
Beerlington
A: 

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.

rugdr
A: 

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

sparky