Oliver
Oliver

Reputation: 1181

Associate two models through foreign key in rails

I have two models in my rails app: report.rb and user.rb

Reports table

id
assigned_user_id
amount
costs
etc.

Users table

id
assigned_user_id
email
prename
etc.

I know how I could associate both models with belongs_to and has_many if I use standard Rails logic (having a user_id on the reports table etc.).

But since I don't have a user_id on the reports table, I would like to connect both tables through assigned_user_id but I don't know now how to specify my association in my models.

Upvotes: 0

Views: 265

Answers (1)

max
max

Reputation: 102016

To alias a 1-to-many association use the foreign_key and class_name options.

class User < ApplicationRecord
  # without foreign_key Rails would look for the inverse 
  # in reports.user_id
  has_many :reports, foreign_key: :assigned_user_id
end

class Report < ApplicationRecord
  # class_name is needed since the class name cannot be deduced by
  # the name of the association
  belongs_to :assigned_user, class_name: 'User'
end

Upvotes: 1

Related Questions