1

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.

4

1 回答 1

5

对于这种情况下的简单数组,最好编写自己的解决方案。

这可以通过覆盖 getter/setter 方法来完成:

在您的模型中:

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

对于哈希,您可以使用ActiveRecord::Store,请参阅http://api.rubyonrails.org/classes/ActiveRecord/Store.html

对于更一般的对象(不仅仅是数组,您可以使用serialize),请参阅http://duanesbrain.blogspot.co.nz/2007/04/ruby-on-rails-persist-array-to-database.html

于 2012-09-04T09:20:57.620 回答