2016-03-04 61 views
1

我有兩個模型,賣家和客戶。 我希望它是一個客戶有一個賣家,許多客戶可以有同一個賣家。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中修改。

可以做出類似的東西嗎?

回答

0

好了,所以一開始,Seller.first.name = "Bud"無助於更新數據庫,即name屬性被設置在Seller.first實例,然後將其丟失,因爲你已經不是分配給任何變量。

所以你需要更改要麼:

Seller.first.update name: "Bud" 

爲了與新的值來更新數據庫,或者更有可能的是這樣的:

seller = Seller.first 
seller.name = "Bud" 
seller.save 

這一步1,實際上將該值保存到數據庫中。

第二個問題是,如果您已經從數據庫中讀取customer.sellers,那麼您的應用程序已經存儲了存儲在內存中的每個name的值,您需要重新加載至少第一條來自DB的記錄,以便獲得新的價值:

customer.sellers.reload 

現在(我假設Seller.first也​​)customer.sellers.first.name"Bud"

+0

由於它的工作;)!但我仍然不能「customer.sellers = seller」,這對我的工作並不重要,但我不明白爲什麼。 –

+0

'customer.sellers'是一個集合,並且您正試圖爲該集合分配一個'seller'。 [你可以在文檔中看到](http://devdocs.io/rails/activerecord/associations/classmethods#method-i-has_and_belongs_to_many)你可以**分配給集合,但你必須分配'objects'對它來說,複數是重要的,你需要將一個集合(一個數組將會工作)分配給集合。 – smathy