视图/控制器平衡 - Rails

时间:2015-12-01 12:02:34

标签: ruby-on-rails ruby view controller

我有一个查询将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

1 个答案:

答案 0 :(得分:1)

由于以下行,客户在加载页面时被添加到类别中:

= link_to "JOIN CATEGORY NOW", root_path(@product.category.add_customer(current_customer)), class: "button4"

或者更具体地说是代码的这一部分:

@product.category.add_customer(current_customer)

因为,当您加载页面时,视图中的Ruby代码会被评估,因此上面的代码会被执行,并且客户会被添加到类别中。

解决方案:

在您的routes.rb中:

resources :categories do
  member do
    get 'add_customer'
  end
end

现在,在您看来:

= link_to "JOIN CATEGORY NOW", add_customer_category_path(@product.category)

CategoriesController

def add_customer
  @category = Category.find(params[:id])
  if @category.add_customer(current_customer)
    redirect_to root_path
  else
    # Redirect user to an error page, maybe?
  end
end