我有兩個模型,賣家和客戶。 我希望它是一個客戶有一個賣家,許多客戶可以有同一個賣家。RAILS-4 - has_and_belongs_to_many
理想情況下,我想可以做customer.seller =賣家 隨着belongs_to協會賣家可以屬於jsute一個客戶。 我使用has_and_belongs_to_many關聯,但我的客戶中只能有一個賣家。
# migration
create_table :sellers do |t|
t.string :name
t.timestamps null: false
end
create_table :customers do |t|
t.string :name
t.timestamps null: false
end
create_table :customers_sellers, id: false do |t|
t.belongs_to :customer, index: true
t.belongs_to :seller, index: true
end
# models/seller.rb
class Seller < ActiveRecord::Base
has_and_belongs_to_many :customers
end
# models/customer.rb
class Customer < ActiveRecord::Base
has_and_belongs_to_many :sellers
end
有了,我不能做這樣的事情:
customer = Customer.create(name: "John")
seller = Seller.create(name: "Dave")
customer.sellers = seller
我有一個錯誤
NoMethodError: undefined method `each' for #<Seller:0x0000000582fb18>
,但我可以:
customer.sellers<< seller
但是,如果我改變賣家的名字,如
Seller.first.name = "Bud"
我希望它也可以在我的customer.sellers.name中修改。
可以做出類似的東西嗎?
由於它的工作;)!但我仍然不能「customer.sellers = seller」,這對我的工作並不重要,但我不明白爲什麼。 –
'customer.sellers'是一個集合,並且您正試圖爲該集合分配一個'seller'。 [你可以在文檔中看到](http://devdocs.io/rails/activerecord/associations/classmethods#method-i-has_and_belongs_to_many)你可以**分配給集合,但你必須分配'objects'對它來說,複數是重要的,你需要將一個集合(一個數組將會工作)分配給集合。 – smathy