【问题标题】:Rails App: Method in model or controllerRails App:模型或控制器中的方法
【发布时间】: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


【解决方案1】:

Rails 方法是让控制器保持精简(非常简单),并尽可能将逻辑添加到模型层。该方法应该在模型中。

关于你的另一个问题:

我可以不将此方法放在购物车控制器中以便购物车对象能够访问它吗?

具体来说,这是一个坏主意。您不希望模型(购物车对象)访问或调用控制器中的任何内容。控制器应该调用(依赖于)模型层,反之则不行。

希望这会有所帮助! :)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多