【发布时间】:2015-12-01 12:02:33
【问题描述】:
我有一个查询将Customer 添加到某个Category。它目前在视图模板中,虽然它可以工作,但有一个错误 - 客户在加载页面时被添加到类别中,在他们点击按钮之前。
我认为将该逻辑移回控制器可能会解决它(使用form_for),然后在视图中呈现提交按钮。
你怎么看?以及如何使用form_for 来实现它?
= link_to "JOIN CATEGORY NOW", root_path(@product.category.add_customer(current_customer)), class: "button4"
编辑: 类别模型
class Category < ActiveRecord::Base
#Associations
belongs_to :product
has_many :customer_categories
has_many :customers, through: :customer_categories
def add_customer(customer_id)
if customer = Customer.where(id: customer_id).first
self.customers << customer unless self.customers.include?(customer)
end
end
end
产品型号
class Product < ActiveRecord::Base
include ActionView::Helpers
#Callbacks
after_create do
Category.create product: self
end
#Associations
has_one :category, dependent: :destroy
客户模型
class Customer < ActiveRecord::Base
#Associations
has_many :customer_categories
has_many :categories, through: :customer_categories
编辑#2:
ActionView::Template::Error (undefined method `add_customer_category' for #<#<Class:0x007fcaebdbb5b0>:0x007fcae377ab90>):
路线:
resources :categories do
member do
get 'add_customer', to: 'categories/add_customer'
end
end
类别控制器:
def add_customer
@product = Product.find(params[:id])
@product.category.add_customer(current_customer.id)
end
【问题讨论】:
标签: ruby-on-rails ruby view controller