Question

I have a Rails4 model (my_model) which may or may not have an attribute. I don't want to save the attribute on my db after I call:

my_model.save

or

my_model.create

but I would like to have access to the value of this possible attribute (or nil if it doesn't exist) after doing:

my_model.new(attribute: possible_attribute)

Is there a way to achieve this result?

Was it helpful?

Solution

Define the possible_attribute as attr_accessor and attr_accessible

class MyModel
  attr_accessor :possible_attribute
  attr_accessible :possible_attribute
end

Now you can do

m = MyModel.new(:possible_attribute => "value")
m.possible_attribute #value

And

m.save

will not save possible_attribute

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