Итак, у меня есть три модели: User
, Event
, которые имеют has_many through
-Ассоциацию через Attendance
. При создании отношения между пользователем и событием в rails console --sandbox
, как user1.attended_events.build(event_id: event1.id)
, я получаю unknown attribute 'event_id' for Event
и наоборот при написании event1.attendees.build(attendee_id: user1.id)
: unknown attribute 'attendee_id' for User
.
Для Attendance
Я создал такую таблицу:
class CreateAttendances < ActiveRecord::Migration[5.1]
def change
create_table :attendances do |t|
t.references :event, foreign_key: true
t.integer :attendee_id
t.timestamps
end
add_index :attendances, :attendee_id
add_index :attendances, [:event_id, :attendee_id], unique: true
end
end
Вот так выглядят мои модели (пользователи также могут создавать события):
User-модель:
class User < ApplicationRecord
has_many :events, inverse_of: "creator", foreign_key: "creator_id" , dependent: :destroy
has_many :attendances, class_name: "Attendance", inverse_of: "attendee", foreign_key: "attendee_id", dependent: :destroy
has_many :attended_events, through: :attendances, source: :event
end
Event-модель:
class Event < ApplicationRecord
belongs_to :creator, class_name: "User", foreign_key: "creator_id"
has_many :attendances
has_many :attendees, through: :attendances
end
Участники-модель:
class Attendance < ApplicationRecord
belongs_to :event, inverse_of: :attendances
belongs_to :attendee, class_name: "User", inverse_of: :attendances
end
Заранее спасибо!