我想将对象传递给过滤器,并希望在create action上使用after_filter更改对象属性。 我只有产品型号有属性,比如名称,标题,价格。一旦添加了产品,我想设置使用after_filter更改价格,那么如何将创建的@product对象传递给过滤方法并更改价格。
class ProductsController < ApplicationController
before_action :set_product, only: [:show, :edit, :update, :destroy]
after_action :change_price, only: [:create] //what should be here..?
# GET /products
# GET /products.json
def index
@products = Product.all
end
# GET /products/1
# GET /products/1.json
def show
end
# GET /products/new
def new
@product = Product.new
end
# GET /products/1/edit
def edit
end
# POST /products
# POST /products.json
def create
@product = Product.new(product_params)
respond_to do |format|
if @product.save
format.html { redirect_to @product, notice: 'Product was successfully created.' }
format.json { render action: 'show', status: :created, location: @product }
else
format.html { render action: 'new' }
format.json { render json: @product.errors, status: :unprocessable_entity }
end
end
end
..
//rest of code
..
private
# Use callbacks to share common setup or constraints between actions.
def set_product
@product = Product.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def product_params
params.require(:product).permit(:name, :category_id)
end
def change_name
//what should be here..? no condition say i want to change every price to 10$
end
end
答案 0 :(得分:0)
您应该使用模型回调after_create
来实现此目标
答案 1 :(得分:0)
实例变量在过滤后立即可用,无需任何操作。因为每个公共操作都创建了一个控制器实例。
但不要这样做。在操作中明确操作您操作的所有内容。过滤器适用于更通用的东西。