rails 4 before_actions 带动态参数
rails 4 before_actions with dynamic parameters
如何使用动态参数设置 before_action 方法,我一直收到错误消息 参数数量错误(0 代表 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
先谢谢你
你可以这样做:
before_action only: [:products, :detail] do
redirect_if_path_has_changed("value")
end
试试这个。当您需要在操作之前设置任何值或其他内容时,上述方法有效。在你的情况下,你想首先从数据库中找到 product
或 detail
然后你想重定向到那个路径。所以 before_action
只是在这两个操作之前调用,这对你的情况没有用。
如何使用动态参数设置 before_action 方法,我一直收到错误消息 参数数量错误(0 代表 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
先谢谢你
你可以这样做:
before_action only: [:products, :detail] do
redirect_if_path_has_changed("value")
end
试试这个。当您需要在操作之前设置任何值或其他内容时,上述方法有效。在你的情况下,你想首先从数据库中找到 product
或 detail
然后你想重定向到那个路径。所以 before_action
只是在这两个操作之前调用,这对你的情况没有用。