我想覆蓋我的關係中的<<
setter。例如,給定:Rails覆蓋關係中的活動記錄集setter
class Library < ActiveRecord::Base
has_many :groups
def readers
groups.find_by(name: 'readers').users
end
end
class Group < ActiveRecord::Base
has_many :group_memberships
has_many :users, through: :group_memberships
end
class GroupMembership < ActiveRecord::Base
belongs_to :user
belongs_to :group
end
class User < ActiveRecord::Base
has_many :groups, through :group_membership
end
我要像做
someLibrary.readers << user1
和一些額外的事情後,這種情況發生。
的代碼應該是這個樣子:
def <<(objects)
super objects
#do other things here
end
它應該在哪裏呢?我想在Group
,如:
class Group
...
def users<<(objects)
super objects
#do stuff
end
end
,但我只是想這樣做,當我在閱讀器調用<<
。
我想知道是否有知道我是否在一組用戶關係調用<<
的方式,或者我是否有權訪問組對象的時候,我就調用用戶組<<
方法通過關係。
我想這樣做,因爲它看起來不錯。最簡單的方法是定義單獨的方法來設置讀者(並且更加明確),但是我想知道在activerecord或ruby中是否有可能。
編輯:
是的,我知道,壓倒一切的核心方法是壞事,人們去地獄的是,亞達內容十分重要。
我只是好奇它是如何完成的。就像爲了學習的目的。
除了目的只是重寫<<
方法在那個特定的關係,所以很可能有人可能會有一些理由爲什麼有人可能會這樣做。
在你的'AR'版本中'someLibrary.readers.class'是什麼? – mudasobwa
恕我直言,覆蓋Rails方法是一個可怕的想法。你爲什麼不添加一個名稱反映它真正做的新方法?你試圖通過重寫Rails核心方法來實現什麼? – spickermann