Finks
Finks

Reputation: 1681

Ruby on Rails model associations

New in rails here. I have trouble understanding this specific activerecord association. Can someone help me on this. The model looks like this:

class User < ActiveRecord::Base
  has_many :client_occurrences,
           foreign_key: "client_id",
           class_name: "Occurrence"
  has_many :requested_occurrences,
           foreign_key: "requestor_id", 
           class_name: "Occurrence"
end

And the one it's associated to is:

class Occurrence < ActiveRecord::Base
  belongs_to :template, autosave: true
  belongs_to :requestor, class_name: "User"
  belongs_to :client, class_name: "User"
end

I just can't seem to understand the associations being portrayed here. Everytime I see the user model, I immediately classify it as an issue because here's how I read the association in the user model:

User has many occurrences alias by client_occurrences and set client_id as foreign_key

It's an issue for me since the foreign_key is not in the proper table (According to my understanding of the code). In addition, client_id and requestor_id are columns found in the Occurrence table.

Could anyone help?

Upvotes: 0

Views: 279

Answers (2)

Peter Alfvin
Peter Alfvin

Reputation: 29399

I'm not sure where your issues are. I would say your reading is correct, namely:

  • User does have many Occurences (each Occurence points back to the User)
  • They are aliased/referenced as client_occurrences from the perspective of the User The foreign_key is indeed client_id.
  • That is, the Occurence table uses client_id to point to the User

From the point of view of Occurrence:

  • Each Occurrence belongs to a :client, which means the field name will be client_id (which matches the foreign_key clause in the User model)
  • The item being pointed to is really a User

One of the things that's confusing, I think, is that the order of the has_many clauses is different from the order of the corresponding belongs_to clauses.

Upvotes: 1

sicks
sicks

Reputation: 767

These are the business rules I gather from that:

A User can be associated with an Occurrence as a client

A User can be associated with an Occurrence as a requestor

A User can be associated to many Occurrences

An Occurrence has one requestor User, and one client User

The foreign key is specified in the User model because it's associated to the same model multiple times, otherwise rails would default to using "user_id" as the foreign key in the Occurrence model.

Check this link out for the full details on what all the different ActiveRecord Associations do: Rails Guides: ActiveRecord Associations

Upvotes: 0

Related Questions