read/write_attribure on associations

Posted by artemave on Stack Overflow See other posts from Stack Overflow or by artemave
Published on 2010-05-07T12:29:17Z Indexed on 2010/05/07 12:38 UTC
Read the original article Hit count: 377

Filed under:

read/write_attribute is a great way to enhance default accessors generated by ActiveRecord. Like this for example:

def price
  read_attribute(:price) or "This item is priceless and you are by the way #{User.current.login}"
end

The same however does not seem to be working with associations. Demonstration:

class Product < ActiveRecord::Base
  has_and_belongs_to_many :stores
end

Then

>> a = Product.first
=> #<Product id: 1, name: "awesome product", created_at: "2010-05-07 12:11:00", updated_at: "2010-05-07 12:11:00">
>> a.stores
=> [#<Store id: 1, name: "ikea", created_at: "2010-05-07 12:11:28", updated_at: "2010-05-07 12:11:28">]
>> a.read_attribute(:stores)
=> nil
>> 

So, is there some sort of read/write_association? Or, if not, is there a reason not to have one?

© Stack Overflow or respective owner

Related posts about ruby-on-rails