ruby-on-rails - 为嵌套资源创建新的 link_to

标签 ruby-on-rails ruby

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

产品型号

class Product < ActiveRecord::Base
  has_many :orders
end

路线.rb

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

产品 View /show.html.erb

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

订单 Controller

class OrdersController < ApplicationController

  def create
    @order = Order.new
  end

end

相关佣金路线:

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

但是当我这样做时,我得到了未定义的方法“new_product_orders_path”

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

最佳答案

在你的 route 添加new action here

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

您的 Controller 也缺少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

关于ruby-on-rails - 为嵌套资源创建新的 link_to,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23847917/

相关文章:

ruby-on-rails - Minitest:Ruby on Rails 中的测试产生的断言比我预期的要多

ruby - 如果没有将 `begin ... end` 用作代码块,Ruby 的 `rescue` 是否会产生意想不到的后果?

ruby - 我有一个 Ruby 对象数组,如何根据这些对象的属性将此数组更改为多个数组?

ruby - 改变哈希值

python - Ruby 是否像 Python 一样具有 `bool` 函数?

javascript - Rails 获取请求无法使用 Angular 正常工作

ruby-on-rails - Heroku 上的 ActiveRecord PGError 不是本地的

java - 从服务器向客户端发送消息

ruby-on-rails - rails 5 : How Do I Get My Error Pages in the Public Folder for Different Locales to Display Other than "en?

ruby-on-rails - has_one 与可选 : true? 的关联