【问题标题】:ActiveModel::MissingAttributeError: can't write unknown attribute `attendee_id`ActiveModel::MissingAttributeError:无法写入未知属性`attendee_id`
【发布时间】: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


【解决方案1】:

好像没有attendee_id

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

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

如果它不能解决问题,我认为,我们需要 moar 堆栈跟踪)

【讨论】:

    【解决方案2】:

    我运行bundle exec rake db:drop,然后创建了数据库bundle exec rake db:createbundle exec rake db:migrate,然后我就可以为数据库播种了。

    【讨论】:

      【解决方案3】:

      请尝试将t.references 更改为特殊别名t.belongs_to
      它适用于 Rails 5.2.1

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-01-14
        相关资源
        最近更新 更多