我有兩個具有這樣關系的模型:
class Ticket < ActiveRecord::Base
belongs_to :group
end
class User < ActiveRecord::Base
has_and_belongs_to_many :groups
has_many :tickets, as: :assignable
end
class Group < ActiveRecord::Base
has_many :tickets, -> { order(:created_at) }
has_and_belongs_to_many :users
end
我需要獲取屬于用戶擁有的相同組的所有票證。我怎樣才能做到這一點?非常感謝!
uj5u.com熱心網友回復:
就目前情況而言,您的關系不完整,因此 Rails 無法正常作業。如果是用戶has_many票證,那么票證必須belong_to(或至少has_one)是用戶。或者,用戶可以使用have_many票證through組,在這種情況下似乎更有可能。
但是,即便如此,您的 Group 模型在做什么也不清楚。特別是,不清楚您打算如何將它與 User 相關聯 - 這看起來是一個相當復雜的關系。
不過,首先,嘗試像這樣設定模型:
class Ticket < ApplicationRecord
belongs_to :group
end
class Group < ApplicationRecord
belongs_to :user
has_many :tickets, dependent: :destroy
end
class User < ApplicationRecord
has_many :groups, dependent: :destroy
has_many :tickets, through: :groups
end
(你會看到我也從 ApplicationRecord 繼承了這些模型,我一直都是這樣做的。)
如果您按上述方式進行設定,則可以通過簡單的@user.tickets.
如果可行,您可以為組和用戶添加額外的 HABTM 關系。但請注意,HABTM 關系可能很復雜,使用它們的方法有好有壞。
(如果您真正想要的主要關系是組 > 用戶 > 票證,請告訴我,我可以相應地進行調整。)
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/314933.html
