I have 3 models, Parent, Children and GrandChildren
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
Each users can create infinite amount of grandchildren, but they can only create one grandchildren for each children.
In my view, I am doing this :
@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
The code above caused my app to do a query everytime i checked whether the children's grand childrens are blank. I searched a bit and found out that I can solve this by using includes.
I tried this :
Parent.includes([childrens: :grand_childrens]).references(:grand_childrens).where("grand_childrens.user_id = (?)",current_user.id)
but it will return only childrens who have grand childrens created by the current user. If a children doesn't have a grand children created by the current user, it won't be included.
I want to get all childrens whether they have grandchildrens created by the current user or not.
I searched around and found this question : Rails includes with conditions. the solution proposed was to create scopes with conditions like this :
has_many :current_user_grand_childrens, :class_name => "GrandChildren",
:conditions => { user_id: current_user.id }
But this would require me to include SessionHelper in models and I would like to avoid that.
Any help is greatly appreciated.