Ruby on rails 将一个模型添加到另一个rails
我正试图想出一种方法,让客户将自己添加到一个类别中。意思-我希望能够在视图中调用@customer。将\添加到\类别(category)或类似内容。有什么建议吗Ruby on rails 将一个模型添加到另一个rails,ruby-on-rails,model,Ruby On Rails,Model,我正试图想出一种方法,让客户将自己添加到一个类别中。意思-我希望能够在视图中调用@customer。将\添加到\类别(category)或类似内容。有什么建议吗 class Category < ActiveRecord::Base #Associations has_many :customers #Defs def add_customer(customer_id) current_customer = Customer.find_by(customer_id: cust
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
类别
在当前架构中,每个类别只能属于一个用户。最好是这样:
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
那么你的分类#添加#客户方法应该是
def add_customer(customer_id)
if customer = Customer.where(id: customer_id).first
self.customers << customer unless self.customers.include?(customer)
end
end
def添加客户(客户id)
如果customer=customer.where(id:customer\u id)。首先
self.customers你也需要这个表。是的,@japed提醒我,这是一个普遍的规则,当你改变你的模式时,你可能需要迁移来添加必要的表/列。这实际上就像liroy在评论中问他是否也需要这个表一样,现在似乎已经不需要了。