Jorge Israel Peña
Jorge Israel Peña

Reputation: 38576

Rails Model Association Confusion

Hey guys. I have the following models:

Events are basically a "log item". In other words, they will store what action was done on what Item by what User in what Category. Naturally, when I thought about this, I figured it "has one User", "has one Category", "has one Item", and so on. However, this would mean that there would be a foreign key for the Event in any given User row, but this isn't what I want. I want the foreign key in the Event row, since the Event is just giving information as to what User, what Category, etc.

So my understanding is that I should instead say that an Event "belongs to a user", "belongs to a category", etc. and that they each "have many Events" in return, correct? I'm just making sure, because this doesn't read logically as most other associations. I don't need/want to be able to access an event from the other side (i.e. user.event) because it wouldn't make much sense. So if I do this, would I just add the belongs_to call and not the has_one on the other side?

Perhaps I designed this incorrectly.

I eventually want to be able to render a 'log page' filled with rows, reach row described a little something like:

event.user event.action event.item event.category

Upvotes: 0

Views: 203

Answers (2)

Aaron Scruggs
Aaron Scruggs

Reputation: 712

Yes, here you want to use a has_many & belongs_to association. In the context of Activerecord, it is the has_many that defines the need for the belongs_to. "If a model (a) has_many of another model (b) then that associated model (b) belongs_to the first model (a)".

Since a user will have many events associated with it, then an event will belong_to a user.

If on the other hand, a user were to only ever have one event associated with it, then these models would have a "has_one" association.

Upvotes: 1

rwilliams
rwilliams

Reputation: 21487

I don't need/want to be able to access an event from the other side (i.e. user.event) because it wouldn't make much sense. So if I do this, would I just add the belongs_to call and not the has_one on the other side?

Add them both(belongs_to and has_many). Sure, user.event doesn't make sense, but user.events does make sense.

Upvotes: 1

Related Questions