簡體   English   中英

使用聯接表中的數據過濾多對多關系的結果

[英]Filtering results of a many to many relationship using data in the join table

我有帶有兩個模型的Rails應用程序,StudentProfile和ClassProfile通過聯接表(模型注冊)關聯。

在我的ClassProfile模型中,我有:

has_many :enrollments
has_many :student_profiles, through: :enrollments

在我的StudentProfile模型中,我有:

has_one :enrollment
has_one :class_profile, through: :enrollment

我的注冊表也有一個狀態整數字段。

我想在ClassProfile模型中放置一個名為“名冊”的方法,該方法返回所有注冊狀態為1的student_profiles。現在,我具有以下內容:

def roster
  self.student_profiles
end

不用說,所有這一切都是讓所有學生返回班級,無論其入學狀況如何。 我覺得這應該很簡單,但是我還沒有看到有關如何在聯接表(注冊)上添加過濾的示例。 這是我可以在ClassProfile模型中完成的事情,還是需要在“注冊”(或其他地方)中做一些事情?

更新

通過查看@QMFNP提到的查詢參考,下面是起作用的代碼:

self.student_profiles.includes(:enrollment).where('enrollments.status = ?', 1)

需要將:enrollments更改為:enrollment因為它是has_one關聯。 我要過濾的enrollments字段是status ,因此將enrollments.id更改為enrollments.status

謝謝!

這可以通過在關聯上指定查詢條件來實現,如下所示:

def roster
  self.student_profiles.includes(:enrollment).where('enrollments.status = ?', 1)
end

這應該返回您的預期結果。 有關查詢Active Record關聯的更多信息,可以在這里找到:

http://guides.rubyonrails.org/active_record_querying.html

希望有幫助!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM