Ricky Mason
Ricky Mason

Reputation: 1828

Return only results based on current object for dynamic menus

If I have an object that has_many - how would I go about getting back only the results that are related to the original results related ids?

Example:

tier_tbl

| id     | name
  1        low
  2        med
  3        high

randomdata_tbl

| id     | tier_id | name
  1        1         xxx
  2        1         yyy
  3        2         zzz

I would like to build a query that returns only, in the case of the above example, rows 1 and 2 from tier_tbl, because only 1 and 2 exist in the tier_id data.

Im new to activerecord, and without a loop, don't know a good way of doing this. Does rails allow for this kind of query building in an easier way?

The reasoning behind this is so that I can list only menu items that relate to the specific object I am dealing with. If the object i am dealing with has only the items contained in randomdata_tbl, there is no reason to display the 3rd tier name. So i'd like to omit it completely. I need to go this direction because of the way the models are set up. The example im dealing with is slightly more complicated.

Thanks

Upvotes: 1

Views: 40

Answers (1)

chumakoff
chumakoff

Reputation: 7044

Lets call your first table tiers and second table randoms

If tier has many randoms and you want to find all tiers whoes id present in table randoms, you can do it that way:

# database query only
Tier.joins(:randoms).uniq

or

  # with some ruby code
  Tier.select{ |t| t.randoms.any? }

Upvotes: 1

Related Questions