【发布时间】:2017-06-05 02:12:20
【问题描述】:
我正在尝试在 User 模型和 Attendee_id 引用用户的出勤模型之间创建关联。该关联是用户和音乐会之间的多对多关系。连接表出勤率有两个字段
:attendee 和 :concert。
seed.rb 文件:
require 'faker'
Concert.destroy_all
User.destroy_all
Attendance.destroy_all
15.times do
Concert.create(band: Faker::RockBand.name, venue: "#{Faker::LordOfTheRings.location}", date: Faker::Date.forward(rand(30)), start_time: "8:00 PM")
end
5.times do |number|
User.create(first_name: Faker::Name.first_name, last_name: Faker::Name.last_name, email: "#{number}@email.com", password: "password")
end
concerts = Concert.all
users = User.all
15.times do
Attendance.create(attendee: users.sample, concert: concerts.sample)
end
以下是模型:
class Attendance < ApplicationRecord
belongs_to :attendee, class_name: "User"
belongs_to :concert
end
class Concert < ApplicationRecord
validates :band, :venue, :date, :start_time, presence: true
has_many :attendances
has_many :attendees, through: :attendances
end
class User < ApplicationRecord
validates :first_name, :last_name, :email, presence: true
validates_format_of :email, with: /@/
has_secure_password
has_many :attendances, foreign_key: :attendee_id
has_many :concerts, through: :attendances
end
这里是迁移:
class CreateAttendances < ActiveRecord::Migration[5.0]
def change
create_table :attendances do |t|
t.references :attendee
t.references :concert, index: true
t.timestamps
end
end
end
class CreateUsers < ActiveRecord::Migration[5.0]
def change
create_table :users do |t|
t.string :first_name
t.string :last_name
t.string :email
t.string :password_digest
t.timestamps
end
end
end
class CreateConcerts < ActiveRecord::Migration[5.0]
def change
create_table :concerts do |t|
t.string :band
t.string :venue
t.datetime :date
t.time :start_time
t.timestamps
end
end
end
【问题讨论】:
-
请移除 sn-ps 并改用正确的代码格式(使用 { } 按钮)。另外,请分享产生错误的代码(很可能是您的控制器)。
-
表示你的一个关联是错误的。
-
@Gerry 感谢您指出这一点。我还没有创建任何控制器,我只是想为数据库做种。
-
@JoshBrody 我不知道我做错了什么。在考勤模型中,我将参加者设置为引用用户。
标签: ruby postgresql ruby-on-rails-5