Search code examples
ruby-on-railsassociationsmodels

Association issue in Rails


I have a problem with rails associations (developing an API).

There are three tables in my_app db:

"tariffs":
 string   "title",
 integer  "tariff_template_id"
...

"tariff_templates":
string   "title",
integer  "service_type_id"
...

"field_templates":
string   "title",
integer  "tariff_template_id"
...

The problem is: I need to get every field_template with tariff_template_id equals to tariff_template_id in "tariffs" table.

It's easy with SQL, but Rails logic is a bit different I guess.

Thanks.


Solution

  • Assuming the associations in your models are set up correctly, sounds like you simply want the following:

    Tariff.includes(:tariff_template).all

    It won't do exactly what you want (Rails works in objects), but it will return you Tariff objects and their associated TariffTemplates in minimal queries.