在 rails 中处理参数丢失异常

Handle parameter missing exception in rails

我有一个类别和产品模型,其中产品模型属于一个类别。目前我在类别显示视图上有一个 link,它将用户带到一个新的产品表单并将类别 ID 设置为用户从 link 编辑 link 的类别。

为了更清楚: 用户选择一个类别 > 用户在类别显示视图上单击新产品 link > 产品表单打开,类别 ID 设置为上一个类别。

我遇到的问题是,如果用户转到 /products/new,它会抛出参数丢失异常,因为无法找到类别 ID(因为地址请求未发送类别)。

有什么方法可以防止用户简单地键入 /products/new 地址并尝试访问表单吗?我想要的是,如果用户在不单击类别页面上的 link 的情况下尝试创建新产品,那么他们将被重定向到主页。

我的产品控制器代码(与此问题相关):

def new
    @product = @category.products.new
  end

def set_category
      @category = Category.find_by(id: params[:category_id]) || Category.find(product_params[:category_id])
      rescue ActiveRecord::RecordNotFound
    end

private
    def product_params
      params.require(:product).permit(:category_id, :title, :description, :image_url, :price)
    end

Link 到类别展示页面上找到的新产品:

  %p= link_to t('.add'), new_product_path(category_id: @category)

异常指向的方法:

def product_params
    params.require(:product).permit(
        :category_id, :title, :description, :image_url, :price)
end

如有任何帮助,我们将不胜感激,如果有一点不清楚,我们深表歉意。

为什么不在您的新操作中添加一个条件来检查参数是否存在?

unless params[:category_id].present?
  redirect_to somewhere
end