0
我有3種型號,父母,子女和孫輩如何只包括孫子申請條件的Rails 4
Class Parent < ActiveRecord::Base
has_many: childrens
end
Class Children < ActiveRecord::Base
belongs_to: parent
has_many: grand_childrens
end
Class GrandChildren < ActiveRecord::Base
belongs_to: children
belongs_to: user
validates :user_id, presence: true
end
每個用戶可以創建孫子的無限量的,但是它們只能爲每個孩子一個孫子。
在我看來,我這樣做:以上
@parents.each do |parent|
parent.childrens.each do |children|
if children.grand_childrens.where("user_id = (?)",current_user.id).blank?
// tells user he has not created grand children for this children
else
//tells user he has created a grand children for this children
end
end
end
的代碼導致我的應用程序做一個查詢,每次我檢查了兒童大的兒童是否是空白。我搜索了一下,發現我可以通過使用includes來解決這個問題。
我嘗試這樣做:
Parent.includes([childrens: :grand_childrens]).references(:grand_childrens).where("grand_childrens.user_id = (?)",current_user.id)
,但它只會返回誰擁有當前用戶創建盛大的兒童兒童。如果一個孩子沒有由當前用戶創建的大孩子,它將不被包括在內。
我想讓所有的孩子都看看他們是否有當前用戶創建的孫輩。
我周圍搜索,發現這個問題:Rails includes with conditions。所提出的解決方案是用這樣的條件下創建範圍:
has_many :current_user_grand_childrens, :class_name => "GrandChildren",
:conditions => { user_id: current_user.id }
但是,這需要我包括SessionHelper在模型和我想避免這種情況。
任何幫助,非常感謝。
用戶創建的模型只是孫子,子女和家長與用戶沒有直接關係。我想把所有的父母和孩子都帶走,但是我只想對grand grandchildrens.user_id = current_user.id申請grand grandchildrens.user_id = current_user.id –
@StefanWijayaD。根據您的評論編輯解決方案 – Anand
是否有可能將此數組返回到activerecord對象?我想訪問像這樣的對象:parent.childrens –