문제

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?

도움이 되었습니까?

해결책

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top