How to make an active record to handle virtual attributes, such as real attributes?

I am quite pleased with the use of virtual attributes in Rails models if they are strings, but I would also like to use other types of attributes, such as dates or booleans, so that I can use helpers like date_select to set virtual attributes.

Is there a good way to do this?

Accordingly, using the date_select helper for a virtual attribute, the following occurs:

1 error(s) on assignment of multiparameter attributes

If I need a boolean attribute, I get @v_attribute = "true", not @v_attr = true.


I found an example somewhere that seemed to work:

class MyModel
  #virtual attribute
  attr_accessor :v_date_field
  attr_accessible :v_date_field

  columns_hash["virtual_date_field"] = ActiveRecord::ConnectionAdapters::Column.new("vi_date_field", nil, "date")
end

But I really don’t know why this works, does it have any side effects, and it looks like hacks.

+5

All Articles