I am setting has_many and belongs_to association in Rails Model: Events(name, identifier, eid) and Users(name, uid)and there is confusion regarding foreign key and primary key. I know what foreign key and primary key means but confused which primary key to use in Events model: eid or uid. I have seen some code on Github where they have added foreign key on User model too. Is it required in my case?
Are migrations required to add these associations?
Given:
- Each User can have many events.
- Each event belongs to a single user.
- Events identifier maps to the user uuid(unique for every user).
- eid is an unique id for every event.
class User < ApplicationRecord
has_many :events, inverse_of: :user
end
class Event < ApplicationRecord
belongs_to :user, foreign_key: :identifier, inverse_of: :events
end
Expected Result:
user = User.first
user.events # Lists all events
event = Event.first
event.user # Outputs first user
uid
- with it you can identify any user definitely. You need to store its value in the events table, and you store it in the identifier column, if I understood you correctly. So looks like you created the correct structure. Do you have any errors when you runevent.user
in the console? – Vasilisaevents
.* FROMevents
WHEREevents
.user_id
= '238329898' – Ashish Goyaluid
andeid
are uuids, not integers? – Vasilisa