Reputation: 1255
I have a Customer, Item and Order model. Customer has_many Items through Orders and has_many Orders. Item has_many Customers through Orders and has_many Orders. Order belongs to Customer and Item. I get the ActiveRecord::UnknownAttributeError: unknown attribute 'customer_id' for Order.
error when trying to save through the console:
Customer model:
class Customer < ActiveRecord::Base
has_many :orders
has_many :items, through: :orders
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
end
Item model:
class Item < ActiveRecord::Base
has_many :orders
has_many :customers, through: :orders
end
Order model:
class Order < ActiveRecord::Base
belongs_to :item
belongs_to :customer
end
Orders table:
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
Console Command to save Order (note that cuban_sandwich and chris are saved as a new Customer and Item already.)
order1 = chris.orders.build(customers_id: chris.id, items_id: cuban_sandwich.id)
Could I be saving this incorrectly? Or is there a problem with my model/table associations?
Upvotes: 0
Views: 2419
Reputation: 25049
Your problem is due to your migration. These lines:
t.belongs_to :customers, index: true
t.belongs_to :items, index: true
create fields called customers_id
and items_id
, not customer_id
and items_id
(note singular vs. plural).
A belongs-to association is a to-one relationship, so it should be singular, customer_id
.
Roll back your migration with rake db:rollback
and change the two belongs_to
calls to be customer
and item
.
Upvotes: 2
Reputation: 4649
First make sure you have customer_id
column on orders
table
rails g migration AddCustomerIdToOrders customer_id:integer
rake db:migrate
Also, I don't believe you need to put the customers_id
as it will be filled in when the association is made. Also you need to use create
not build
instead of this
order1 = chris.orders.build(customers_id: chris.id, items_id: cuban_sandwich.id)
try this
order1 = chris.orders.create(items_id: cuban_sandwich.id)
Upvotes: 2