2015-02-07 48 views
0

如何设置before_action方法与动态参数,可以一直收到错误错误的参数数目(0 1)轨道4个before_actions动态参数

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 

回答

0

谢谢您能做到这样的:

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

试试这个。当你需要在动作之前设置任何值或其他东西时,上述工作。在你的情况下,你想首先从数据库中找到productdetail,然后你想重定向到那个路径。所以before_action只是在你的情况下没有用的两个动作之前调用。

+0

我尝试你的解决方案,但它不工作sir :( – junior 2015-02-07 04:42:50

+0

或者是否有任何其他方式如何重构我的代码? – junior 2015-02-07 04:46:32

+0

我不明白你为什么要在'before_action'中调用它,因为你再次手动调用它在'products'和'detail'动作中,我认为'before_action'不是必须的,如果你这样做的话 – Deep 2015-02-07 04:48:44