2015-11-02 83 views
0

我試圖想出一種讓客戶將自己添加到類別的方法。含義 - 我希望能夠在我的views @ customer.add_to_category(category)或類似的地方打電話。有什麼建議麼?將另一個模型添加到另一個導軌

class Category < ActiveRecord::Base 
#Associations 


has_many :customers 

#Defs 
def add_customer(customer_id) 
    current_customer = Customer.find_by(customer_id: customer_id) 
    if current_customer 
     current_customer = Customer.build(customer_id: customer_id) 
    end 
    current_customer 
end 
end 

回答

2

在您當前的架構中,每個類別只能屬於一個用戶。這將是最好能有像這樣:

Customer 
    has_many :customer_categories 
    has_many :categories, :through => :customer_categories 

Category 
    has_many :customer_categories 
    has_many :customers, :through => :customer_categories 

CustomerCategory 
    belongs_to :customer 
    belongs_to :category 

那麼你的類別#add_customer方法應該只是

def add_customer(customer_id) 
    if customer = Customer.where(id: customer_id).first 
    self.customers << customer unless self.customers.include?(customer) 
    end 
end 

你可以做的這反過來在客戶類,效果顯着。

+0

你也需要這張表。 –

+0

是的,正如@japed提醒我的那樣,一般來說,當您更改模式時,您可能需要進行遷移才能添加必要的表/列。 –

+0

這實際上是因爲裏裏問他在評論中是否也需要表格,現在似乎已經過去了。 –

相關問題