2015-02-07 49 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