Rails 5 serialized attributes
Can we have a column in our model without making it a column in our table ??
Well, The answer is Yes.
In order to use any column in your model without making it a column in your table, you have to add a column ex:serialized_options (you can name it anything) with data type set to text in your table.
Also, you have to tell serialized_options column to store your column names
in your model.
store :serialized_options ,accessors: [:column_name1,:column_name2]
Store gives you a thin wrapper around serialize for the purpose of storing hashes in a single column. It’s like a simple key/value store baked into your record when you don’t care about being able to query that store outside the context of a single record.
Now your serialized options attribute will store password_reset_token and password_reset_sent_at.You can access that with your model name
Example:
- In your user table add column serialized_options
In your user model add
store :serialized_options, accessors [:password_reset_token,:password_reset_sent_at], coder: Hash
- For key accessors: [:you can add any column you want to access from user model’s object]
- Coder can be Hash or JSON,default is hash.
- Now you can access the desired columns without adding them to users table.
u = User.last
u.password_reset_token
Reference: http://api.rubyonrails.org/classes/ActiveRecord/Store.html