What is the right way to override a setter method in Ruby on Rails?

前端 未结 5 849
春和景丽
春和景丽 2020-11-28 18:05

I am using Ruby on Rails 3.2.2 and I would like to know if the following is a \"proper\"/\"correct\"/\"sure\" way to override a setter method for a my class attribute.

5条回答
  •  旧巷少年郎
    2020-11-28 19:03

    I have found that (at least for ActiveRecord relationship collections) the following pattern works:

    has_many :specialties
    
    def specialty_ids=(values)
      super values.uniq.first(3)
    end
    

    (This grabs the first 3 non-duplicate entries in the array passed.)

提交回复
热议问题