muichkine
muichkine

Reputation: 2940

Override model attribute

Here is the thing. I have a Country model with two columns "languages" and "default_language". So for instance, for switzerland these columns are set respectively to "de,fr,it" and "de".

Now, if I do Country.languages I get the "de,fr,it" string. How can I override this so when I get Country.languages I get an array ["de","fr","it"] ?

Sure I could create a function def available_languages, but still, I don't want languages to be public.

Upvotes: 1

Views: 739

Answers (1)

ronalchn
ronalchn

Reputation: 12335

For simple arrays in this case, it is probably better to write your own solution.

This can be done by overriding the getter/setter methods:

In your model:

class Country < ActiveRecord::Base
  def languages
    read_attribute(:languages).split(',')
  end
  def languages=(array)
    write_attribute(:languages,array.join(','))
  end
end

For hashes, you can use ActiveRecord::Store, see http://api.rubyonrails.org/classes/ActiveRecord/Store.html

For more general objects (not just arrays, you can use serialize), see http://duanesbrain.blogspot.co.nz/2007/04/ruby-on-rails-persist-array-to-database.html

Upvotes: 5

Related Questions