Rails 如何在 Rails4 里设置 nested resourced?

foxzool · August 14, 2013 · Last by Rei replied at August 14, 2013 · 2391 hits

使用 rails4.0 在 routes 里设置

resources :shops do
  resources :products
end

在使用 scaffold 生成的 product controller 里

# POST /products
# POST /products.json
def create
  @product = Product.new(product_params)

  respond_to do |format|
    if @product.save
      format.html { redirect_to @product, notice: 'Product was successfully created.' }
      format.json { render action: 'show', status: :created, location: @product }
    else
      format.html { render action: 'new' }
      format.json { render json: @product.errors, status: :unprocessable_entity }
    end
  end
end


private
def product_params
   params.require(:product).permit(:name, :shop_id, :price)
end

问题: 默认通过 Product.new(product_params) 生成的@product变量, 当 redirect_to @product 时,默认是跳转 product_path。我需要将其跳转为 shop_product_path。

所以,如何正确的设置 product_params?

namespace :shop do
  resources :products
end

1 楼 -1

明显楼主是要保留 nested resources 的嘛 /shops/1/products/122 用 namespace 就变成了 shop/products/122

其实楼主的问题我也想知道答案。。

这貌似跟 product_params 一点关系都没有吧……

def create
    @shop = Shop.find params[:shop_id]
    @product = @shop.products.new(product_params)

    respond_to do |format|
      if @product.save
        format.html { redirect_to shop_product_url(@shop, @product), notice: 'Product was successfully created.' }
You need to Sign in before reply, if you don't have an account, please Sign up first.