【发布时间】:2015-09-16 13:45:08
【问题描述】:
我是一名初学者,并按照“Rails 中的敏捷 Web 开发”一书并创建了一个书店应用程序。在此过程中,我将购物车更改为“更智能”,方法是在购物车中添加书籍数量并为同一产品的多个项目设置一个订单项。
本书推荐(但不解释),在 carts 模型中放置一个添加产品的方法,并在 line_items 控制器中的 cart 对象上调用它。我可以不将此方法放在购物车控制器中以便购物车对象能够访问它吗?是一种方法比另一种更好,还是一种偏好?
这是型号代码:
class Cart < ActiveRecord::Base
has_many :line_items, dependent: :destroy
def add_product(product_id)
current_item = line_items.find_by_product_id(product_id)
if current_item
current_item.quantity = +1
else
current_item = line_items.build(product_id: product_id)
end
current_item
end
end
这是控制器代码:
class LineItemsController < ApplicationController
before_action :set_line_item, only: [:show, :edit, :update, :destroy]
def create
@cart = current_cart
product = Product.find(params[:product_id])
@line_item = @cart.add_product(product.id)
@line_item.product = product
respond_to do |format|
if @line_item.save
format.html { redirect_to @line_item.cart, notice: 'Line item was successfully created.' }
format.json { render :show, status: :created, location: @line_item }
else
format.html { render :new }
format.json { render json: @line_item.errors, status: :unprocessable_entity }
end
end
end
【问题讨论】:
-
大部分逻辑都应该放在模型层。您的控制器应该非常简单,它们的工作基本上是将请求转换为正确模型上的方法调用,并呈现结果。
标签: ruby-on-rails model controller