Reputation: 4013
I have the following query
SubCategory.joins(dropdown_heads: :dropdown_lists).where(id: params[:sub_cat_id])
The above query generates
SELECT "sub_categories".* FROM "sub_categories" INNER JOIN "dropdown_heads" ON "dropdown_heads"."sub_category_id" = "sub_categories"."id" INNER JOIN "dropdown_lists" ON "dropdown_lists"."dropdown_head_id" = "dropdown_heads"."id" WHERE "sub_categories"."id" = 6
But what I actually need is to fetch records from dropdown_heads
and dropdown_lists
only.
What modification do I need to achieve it?
Following are the associations
sub_category.rb
has_many: dropdown_heads
dropdown_head.rb
has_many: dropdown_lists
belongs_to: sub_category
dropdown_lists.rb
belongs_to: dropdown_head
Upvotes: 1
Views: 1301
Reputation: 802
You can use
SubCategory.joins(dropdown_heads: :dropdown_lists).where(id: params[:sub_cat_id].select("dropdown_heads.dropdown_heads, dropdown_lists.dropdown_lists")
Even you can use pluck()
method of rails to retrieve specific fields.
Upvotes: 0
Reputation: 1692
You don't have to get the sub_category instance, you can just call
dropdown_heads = DropdownHead.find_all_by_sub_category_id(params[:sub_cat_id])
and the remaining are just the same as @rb512 said.
Upvotes: 0
Reputation: 6948
Retrieve the sub_category record from the database
@sub_category = SubCategory.find(params[:sub_cat_id])
Retrieve all dropdown_heads
sub_category.dropdown_heads
Iterate through dropdown_head to retrieve dropdown_lists
@sub_category.dropdown_heads {|dropdown_head| dropdown_head.dropdown_lists} #do whatever you want with dropdown_lists
which is same as:
@sub_category.dropdown_heads.each |dropdown_head|
dropdown_head.dropdown_lists
end
Upvotes: 1