ruby-on-rails – 小型控制器上的代码重构(瘦控制器胖模型)
发布时间:2020-12-17 03:06:18 所属栏目:百科 来源:网络整理
导读:我有一个控制器动作,正在进行产品列表,分页和一些过滤器,如类别(从下拉列表),标题(从文本字段),股票(从复选框) 这是我的控制器: class ProductsController ApplicationController def index @products = Product.where(active:1).where("title LIKE ?","%#{
我有一个控制器动作,正在进行产品列表,分页和一些过滤器,如类别(从下拉列表),标题(从文本字段),股票(从复选框)
这是我的控制器: class ProductsController < ApplicationController def index @products = Product.where(active:1).where("title LIKE ?","%#{params[:title]}%") if params[:stock] @products=@products.where("stock = 0") end if params[:category] @products=@products.where("category_id LIKE ?","#{params[:category]}") end @products= @products.paginate(:page => params[:page]) @categories= Category.all end 我的模型是: class Product < ActiveRecord::Base belongs_to :category ...some validations... end 为了让我的控制器变得更薄,我可以改变什么?谢谢 解决方法
模型
class Product < ActiveRecord:::Base scope :active,where(active: 1) def self.with_stock(stock=nil) return where(stock: 0) if stock self end def self.categorized(category=nil) return self.where(category: category) if category self end def self.titled(title=nil) return self.where("title LIKE ?",'title') if title self end def self.list(params) title = params[:title] category = params[:category] page = params[:page] self.titled(title).with_stock(stock).categorized(category) .paginate(page).active end end 调节器 def index @products = Product.list(params) end 不要在控制器中发运类别.在模板/部分中执行.仅来自控制器的一个实例变量. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |