Reputation: 143
I have two models namely Leave
and Calendar
. These two models have has_and_belongs_to many association. I am trying to create the join table for this relation named calendars_leaves
.
Now the problem that I am facing is it creates column named leafe_id
instead of leave_id
.
Any idea how to can I solve this issue.
Here are my models
class Leave < ApplicationRecord
belongs_to :user
has_and_belongs_to_many :calendars, foreign_key: 'calendar_id'
self.table_name = 'leaves'
self.primary_key = 'leave_id'
end
class Calendar < ApplicationRecord
has_and_belongs_to_many :users
has_and_belongs_to_many :leaves, class_name: 'Leave', foreign_key: 'leave_id'
validates :name, :description, presence: true, length: { minimum: 3 }
end
Upvotes: 2
Views: 440
Reputation: 3603
ActiveRecord resolves tables with 'ves' to singular model class with 'f' by default. Hence a table named leaves
is resolved to ActiveRecord model class Leaf
So, for custom behaviour of these incorrect assumed translations, you need to configure it on your app's config/initializers/inflections.rb
file.
ActiveSupport::Inflector.inflections do |inflect|
inflect.irregular 'leave', 'leaves'
end
After configuring your app with this inflection and restarting your app's web server, rails will recognize Leave
as the ActiveRecord model defined in app/models/leave.rb
representing db table leaves
and you can use leave_id
as foreign key for defining associations between your models.
Read more about inflections here
Upvotes: 1