2
votes

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:

  1. Each User can have many events.
  2. Each event belongs to a single user.
  3. Events identifier maps to the user uuid(unique for every user).
  4. 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
1
Primary_key for users table is 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 run event.user in the console?Vasilisa
@Vasilisa For User.first.events it shows ActiveRecord::StatementInvalid: Mysql2::Error: Unknown column 'events.user_id' in 'where clause': SELECT events.* FROM events WHERE events.user_id = '238329898'Ashish Goyal
Which types have columns 'uid' and 'identifier'?Vasilisa
Do I understand correctly, that uid and eid are uuids, not integers?Vasilisa
Yes, they are uuids. They are of string type. I changed there name here to get a better understandingAshish Goyal

1 Answers

0
votes

You should use the column in the users table, which uniquely identifies the users. As I read you post that is uid, in that case your code should look something like this:

class User < ApplicationRecord
  has_many :events, inverse_of: :event
end

class Events < ApplicationRecord
  belongs_to :user, foreign_key: :uid, inverse_of: :user
end

Hope this helps.