[英]ruby on rails, has_many, define class name for polymorphic relationship
[英]Rails aggregating polymorphic has_many relationship
在我的應用中, Account
可以由Household
或User
。 用戶可以訪問自己擁有的帳戶以及家庭擁有的帳戶。 我已經定義了accessible_accounts
,它為我提供了家庭帳戶和用戶帳戶的數組,但是有沒有辦法獲得與關系相同的結果,因此我可以將其與其他條件鏈接起來嗎? 順序並不重要(實際上可以通過進一步的鏈接設置)
class User < ActiveRecord::Base
has_many :accounts, as: :owner
belongs_to :household
def accessible_accounts
ua = accounts.to_a
ha = []
if household
ha = household.accounts.to_a
end
(ua + ha).uniq
end
end
class Household < ActiveRecord::Base
has_many :users
has_many :accounts, as: :owner
end
class Account < ActiveRecord::Base
belongs_to :owner, polymorphic: true
end
我對此有幾點想法:
首先,你可以表達的Account
即User
必須通過Household
通過添加以下的Accounts
模型:
has_many :accounts, through: household
但是,我知道您想要一個Relation
,它代表用戶直接擁有的帳戶與他們通過關聯家庭擁有的帳戶的合並/聯合。 如果是這樣,那么我認為添加到User
的以下方法將為您提供所需的內容:
def accessible_accounts
Account.where(
'(ownable_id = ? and ownable_type = ?) or (ownable_id = ? and ownable_type = ?)',
id, User.to_s, household_id, Household.to_s)
end
我尚未對此進行測試,但我認為如果我誤解了一些內容,可以繼續分享並依靠反饋。
在適當的多態關聯中,我認為您的結構將如下所示:
class User < ActiveRecord::Base
belongs_to :household
has_many :accounts, as: :ownable
end
class Household < ActiveRecord::Base
has_many :users
has_many :accounts, as: :ownable
end
class Account < ActiveRecord::Base
belongs_to :ownable, polymorphic: true
end
順便說一句,您是否有不使用Devise和CanCan進行身份驗證和授權的特殊原因?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.