为嵌套资源创建新的link_to

时间:2014-05-24 17:36:45

标签: ruby-on-rails ruby

我尝试使用link_to帮助程序函数为特定产品创建新订单。这是我的:

产品型号

class Product < ActiveRecord::Base
  has_many :orders
end

的routes.rb

resources :products, :only => [:show, :new, :create, :index, :update, :destroy] do
    resources :orders, :only => [:create]
  end

查看产品/ show.html.erb

<%= link_to 'New Order', new_product_orders_path(@product) %>

订单控制器

class OrdersController < ApplicationController

  def create
    @order = Order.new
  end

end

相关的佣金路线:

product_orders POST   /products/:product_id/orders(.:format)                                     orders#create

但是当我这样做时,我得到了未定义的方法`new_product_orders_path&#39;

在Rails 4中执行此操作的正确方法是什么?

2 个答案:

答案 0 :(得分:4)

在您的路线中,在此处添加new操作

resources :orders, :only => [:create, :new]

您的控制器在您保存记录所需的new操作中缺少create操作

class OrdersController < ApplicationController

  before_filter :set_product

  def new
    @order = @product.orders.new
  end

  def create
    @order = @product.orders.new(params[:order])
    @order.save
  end

  private

    def set_product
      @product = Product.where("id =?", params[:product_id]).first
    end

end

答案 1 :(得分:1)

我认为你需要

    resources :products, :only => [:show, :new, :create, :index, :update, :destroy] do
      resources :orders, :only => [:create, :new]
    end

您还可以在服务器路径末尾键入“/ rails / info / routes”来检查路由。