0

In a new rails app, I have to build this sort of relationship

Trip -> 1-to-1 -> Plan
Plan -> n-to-n -> Places
Plan -> n-to-n -> Activities

and ofcourse the vice-versa relationship as well..

The plan table is something I'm thinking about. Whether it is possible to have a direct Trip -> Places and Trip -> Activities relationship without any extra table.

If not, then what could be and efficient way to handle this kind of relationship, keeping in mind that there might be other models which could have a n-to-n relationship with the Plan model in the future.

UPDATE - I found this question and the answer to work. Might be helpful for someone looking to do the same as I am

ActiveRecord, has_many :through, and Polymorphic Associations

Thank you

Community
  • 1
  • 1
hashpipe
  • 305
  • 3
  • 16

1 Answers1

3

It's possible, but complicated and messy, so I wouldn't. You can define has_many ..., :through => :plan associations to easily and efficiently access the places and activities for trips, etc.

Rails doesn't offer the :through option for belong_to associations, but you can define convenience methods to access those, and you can query the associated records efficiently by using the :include option when finding.

Steve Jorgensen
  • 11,725
  • 1
  • 33
  • 43
  • but won't the has_many :through => :plan require a place_id and activity_id in the plan table ? Wouldn't that be a problem ? I was wondering if I could have a generic x_id & x_type column in the plan table and then setup the has_many :through => :plan association. Would this be possible ? – hashpipe May 07 '12 at 07:16
  • @hashpipe With the `:through` => option, ActiveRecord examines the model you are associating through to determine how it is related to the target model. I just tried this to confirm in Rails 3.2.3. I created an `Aaa` model that belongs to `:bbbs`, a `Bbb` model that has and belongs to many `:cccs`, and then set `Aaa` have and belong to many `:cccs` through `:bbb`. I am then able to execute `Aaa.first.cccs`, and the SQL is `SELECT "cccs".* FROM "cccs" INNER JOIN "bbbs_cccs" ON "cccs"."id" = "bbbs_cccs"."ccc_id" INNER JOIN "bbbs" ON "bbbs_cccs"."bbb_id" = "bbbs"."id" WHERE "bbbs"."id" = 1` – Steve Jorgensen May 07 '12 at 14:03