diya
diya

Reputation: 7138

How to keep a transient variable as part of ActiveRecord

I would like to show a variable (which is actually a List) as part of f.select(..) function in Rails3.2, so that the selected value is stored in a different attribute in the ActiveRecord object. How do I declare the above List variable as a transient variable in ActiveRecord, so that ActiveRecord doesn't try to store this.

Upvotes: 3

Views: 3144

Answers (2)

gwnp
gwnp

Reputation: 1216

In rails 4+, you can define a transient field in your model simply via:

attr_accessor :the_field

Upvotes: 4

joshblour
joshblour

Reputation: 1034

You can write your own getter and setter methods in the model like this (don't forget to add it to attr_accessible):

def virtual_attr=(value)
  self.real_attr = value
end

def virtual_attr
  self.real_attr
end

or just create an alias for the real attribute, like this:

alias_attribute :virtual_attr, :real_attr

Upvotes: 2

Related Questions