[英]Rails App: Method in model or controller
我是一名初學者,正在閱讀“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
Rails 的方法是保持控制器瘦(非常簡單)並盡可能向模型層添加邏輯。 這個方法應該在模型中。
對於你的另一個問題:
我可以不將此方法放在購物車控制器中以便購物車對象能夠訪問它嗎?
具體來說,這是一個壞主意。 您不希望模型(購物車對象)訪問或調用控制器中的任何內容。 控制器應該調用(依賴於)模型層,但反之則不然。
希望這可以幫助! :)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.