1

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

3 Answers 3

1

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
Sign up to request clarification or add additional context in comments.

9 Comments

you only need to get sub_category from the controller. once you have the correct sub_category object, you can do the rest in your views
Had this in my view <%= sub_category.dropdown_heads %> but throwing exception undefined local variable or method sub_category'`
make sub_category an instance variable (add "@" prefix, see my updated answer)
I cant understand what is happening in your third code. Can you please explain it
To reduce the number of SQL queries, you can use eager-loading: @sub_category.dropdown_heads.includes(:dropdown_lists)
|
0

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.