假設我們有以下關系:
class Users < ActiveRecord::Base
has_many :meetings
has_many :events
end
class Meetings < ActiveRecord::Base
scope :is_morning_meeting, -> { where.some.condition }
end
class Events < ActiveRecord::Base
scope :is_morning_event, -> { where.some.condition }
end
有沒有辦法讓我抓取整個User物件,但指定is_morning_*這些關聯的范圍。
就像是:
class Users < ActiveRecord::Base
has_many :meetings, -> () { is_morning_meeting if scope.morning_concerns }
has_many :events, -> () { is_morning_event if scope.morning_concerns }
scope :morning_concerns
end
像這樣使用:
morning_user = user.morning_concerns
如果我打電話
morning_user.meetings
它應該只回傳早上的會議
如果我打電話
morning_user.events
它應該只回傳早上的事件
這可能看起來有點具體,但由于 GraphQL 決議流程,我發現自己被逼到了絕境。
uj5u.com熱心網友回復:
您可以像這樣定義自定義has_many關聯scope:
class Users < ActiveRecord::Base
has_many :meetings
has_many :morning_meetings, -> { is_morning_meeting }, class_name: "Meeting"
has_many :events
has_many :morning_events, -> { is_morning_event }, class_name: "Event"
end
并且可以像普通關聯一樣簡單地呼叫這些關聯:
user.morning_meetings
user.morning_events
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/535918.html
標籤:ruby-on-rails红宝石活动记录ruby-on-rails-5
