简体   繁体   中英

rails 4 before_actions with dynamic parameters

How to set a before_action method with dynamic params, I keep getting an error wrong number of arguments (0 for 1)

class PagesController < ApplicationController
  before_action :set_categories
  before_action :redirect_if_path_has_changed, only: [:products, :detail]

  def home
  end

  def products
    @category = Category.find(params[:id])
    @products = @category.products.order("created_at").page(params[:page]).per(6)

    redirect_if_path_has_changed(products_by_category_path(@category))
  end

  def detail
    @product = Product.find(params[:id])

    redirect_if_path_has_changed(product_details_path(@product))
  end

  private

  def set_categories
    @categories = Category.all
  end

  def redirect_if_path_has_changed(path_requested)
    redirect_to path_requested, status: :moved_permanently if request.path != path_requested
  end
end

Thank you before

You can do it like this:

before_action only: [:products, :detail] do
  redirect_if_path_has_changed("value")
end

Try this. The above works when you need to set any value or something before the action. In you case you want to first find the product or detail from database then you want to redirect to that path. So before_action just calls before the two actions which is not useful in your case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM