【发布时间】:2020-03-30 18:01:30
【问题描述】:
我正在尝试在 RoR 程序中建立 多对多 关联,但我无法摆脱标题中提到的错误,即我在Rails 控制台是:
User.find(1).attended_events = [Event.find(1)]
我需要解决这个问题,但找不到任何地方,感谢任何帮助。
我的代码:
模型
class User < ApplicationRecord
has_many :created_events,class_name:"Event"
has_many :hosts
has_many :attended_events, through: :hosts
end
class Host < ApplicationRecord
belongs_to :attended_event, class_name:"Event"
belongs_to :attendee, class_name:"User"
end
class Event < ApplicationRecord
belongs_to :creator, foreign_key: :user_id, class_name:'User'
has_many :hosts
has_many :attendees, through: :hosts
end
迁移文件
class CreateUsers < ActiveRecord::Migration[6.0]
def change
create_table :users do |t|
t.string :name
t.string :email
t.timestamps
end
end
end
class CreateHosts < ActiveRecord::Migration[6.0]
def change
create_table :hosts do |t|
t.references :attendee, null: false, foreign_key: true
t.references :attended_event, null: false, foreign_key: true
t.integer :user_id
t.integer :event_id
t.timestamps
end
end
end
class CreateEvents < ActiveRecord::Migration[6.0]
def change
create_table :events do |t|
t.string :date
t.text :description
t.references :user, null: false, foreign_key: true
t.timestamps
end
end
end
【问题讨论】:
标签: ruby-on-rails model migration many-to-many associations