ActiveModel :: MissingAttributeError:无法写入未知属性`attendee_id`

时间:2017-06-05 02:12:21

标签: ruby postgresql ruby-on-rails-5

我正在尝试在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

3 个答案:

答案 0 :(得分:2)

看起来没有attendee_id

bundle exec rails db:reset(与db:drop + db:create + db:migrate + db:seed相同

对于测试bundle exec rails db:test:prepare

如果它没有解决问题,我想,我们需要moar stacktraces)

答案 1 :(得分:0)

我运行bundle exec rake db:create然后我创建了数据库bundle exec rake db:migrate socket.on('update', function(data) { birds.update(data.birds); pipes.update(data.pipes); 然后我就可以为数据库设定种子。

答案 2 :(得分:0)

请尝试将records.add()更改为特殊别名write()
它适用于Rails 5.2.1