Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/54.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 如何在rails中将对象传递到filters方法中_Ruby On Rails_Ruby_Ruby On Rails 4 - Fatal编程技术网

Ruby on rails 如何在rails中将对象传递到filters方法中

Ruby on rails 如何在rails中将对象传递到filters方法中,ruby-on-rails,ruby,ruby-on-rails-4,Ruby On Rails,Ruby,Ruby On Rails 4,我想将对象传递到过滤器中,并想在创建操作上使用after_filter更改对象属性。 简单地说,我的产品模型具有名称、标题、价格等属性。添加产品后,我想使用after_filter设置更改价格,因此如何将创建的@Product对象传递到filter方法并更改价格 class ProductsController < ApplicationController before_action :set_product, only: [:show, :edit, :update, :destr

我想将对象传递到过滤器中,并想在创建操作上使用after_filter更改对象属性。 简单地说,我的产品模型具有名称、标题、价格等属性。添加产品后,我想使用after_filter设置更改价格,因此如何将创建的@Product对象传递到filter方法并更改价格

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
class ProductsController
您应该在创建后使用模型回调
来实现这一点

实例变量在after filter中立即可用,无需执行任何操作。因为每个公共操作都创建了一个控制器实例


但不要那样做。在动作中明确地操纵一切。过滤器用于更一般的东西。

我不认为过滤器的目的是改变对象的状态。我知道..我只是想知道如何将对象传递到过滤器方法..这是我在这里使用的一个示例,以了解..在您的示例中,@产品将在后过滤器中可用,因为它是在创建方法