【问题标题】:ActiveRecord::UnknownAttributeError: unknown attribute 'customer_id' for OrderActiveRecord::UnknownAttributeError:订单的未知属性“customer_id”
【发布时间】:2016-02-25 10:10:18
【问题描述】:

我有一个 Customer、Item 和 Order 模型。 Customer has_many Items 通过 Orders 和 has_many Orders。项目 has_many Customers through Orders 和 has_many Orders。订单属于客户和项目。尝试通过控制台保存时出现ActiveRecord::UnknownAttributeError: unknown attribute 'customer_id' for Order. 错误:

客户模型:

class Customer < ActiveRecord::Base
  has_many :orders
  has_many :items, through: :orders

  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

end

物品型号:

class Item < ActiveRecord::Base
  has_many :orders
  has_many :customers, through: :orders
end

订购模型:

class Order < ActiveRecord::Base
  belongs_to :item
  belongs_to :customer
end

订单表:

class CreateOrders < ActiveRecord::Migration
  def change
    create_table :orders, id: false do |t|
      t.belongs_to :customers, index: true
      t.belongs_to :items, index: true
      t.timestamps null: false
    end
  end
end

保存订单的控制台命令 (注意 cuban_sandwich 和 chris 已经被保存为一个新的 Customer 和 Item。)

order1 = chris.orders.build(customers_id: chris.id, items_id: cuban_sandwich.id)

我会错误地保存这个吗?还是我的模型/表格关联有问题?

【问题讨论】:

    标签: ruby-on-rails activerecord


    【解决方案1】:

    您的问题是由于您的迁移造成的。这些行:

    t.belongs_to :customers, index: true
    t.belongs_to :items, index: true
    

    创建名为 customers_iditems_id 的字段,而不是 customer_iditems_id(注意单数与复数)。

    belongs-to 关联是一对一的关系,所以应该是单数,customer_id

    使用rake db:rollback 回滚您的迁移并将两个belongs_to 调用更改为customeritem

    【讨论】:

      【解决方案2】:

      首先确保orders 表上有customer_id

      rails g migration AddCustomerIdToOrders customer_id:integer
      rake db:migrate
      

      另外,我认为您不需要输入customers_id,因为它会在建立关联时填写。您还需要使用create 而不是build

      而不是这个

      order1 = chris.orders.build(customers_id: chris.id, items_id: cuban_sandwich.id)
      

      试试这个

      order1 = chris.orders.create(items_id: cuban_sandwich.id)
      

      【讨论】:

      • 对不起,我错过了你的那部分错误。我也更新了我的答案来解决这个问题
      • #&lt;Order customers_id: nil, items_id: 2, created_at: "2016-02-25 02:11:08", updated_at: "2016-02-25 02:11:08", customer_id: 1&gt; 我应该删除 t.belongs_to :customers, index: true 吗?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-10
      • 2013-04-09
      • 2021-11-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多