将一个模型添加到另一个轨道

时间:2015-11-02 12:07:08

标签: ruby-on-rails model

我正试图想出一种让顾客将自己添加到某个类别的方法。含义 - 我希望能够在我的观点中调用@ customer.add_to_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

1 个答案:

答案 0 :(得分: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

然后你的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  

显然,您可以在Customer类中进行相反的操作。