Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/66.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 如何在创建父对象后创建多个子对象?_Ruby On Rails_Ruby_Forms_Activerecord_Nested Attributes - Fatal编程技术网

Ruby on rails 如何在创建父对象后创建多个子对象?

Ruby on rails 如何在创建父对象后创建多个子对象?,ruby-on-rails,ruby,forms,activerecord,nested-attributes,Ruby On Rails,Ruby,Forms,Activerecord,Nested Attributes,这是我的设想: 我有一个订单模型和一个项目模型。它们之间有以下关系: class Order < ApplicationRecord has_many :items end class Item < ApplicationRecord belongs_to :order end 类顺序

这是我的设想:

我有一个订单模型和一个项目模型。它们之间有以下关系:

class Order < ApplicationRecord
    has_many :items
end

class Item < ApplicationRecord
    belongs_to :order
end
类顺序
在我的项目中,最初,我需要创建没有项目的订单。之后,我需要创建与该订单相关的项目

我已经尝试了用户嵌套的_属性,但是,我需要多次创建项目,第二次尝试时,我已经创建的项目会显示在表单中以供编辑

关于最佳方法有什么建议吗

编辑:


再添加一个信息。我需要一次创建多个项目的选项。

一个选项可以是先创建订单,然后创建项目

# config/routes
...
resources :orders do
  resources :items
end

# app/controllers/itesm_controller.rb
class ItemsController < ApplicationController
  def new
    order = Order.find(params[:order_id]
    @item = order.items.new
  end

  def create
    item.create(item_params)
    redirect_to orders_path # just guessing your paths
  end

  protected

  def item_params
    params.require(:item).permit(:your, :attributes, :here)
  end
end

# Assuming Rails +5.1
# app/views/items/_form.html.erb
# you can use this partial in 'new.html.erb' and 'edit.html.erb'

<%= form_view model: @item do |form| %>
  <%= form.label :your_attribute %>
  <%= form.text_field :your_attribute %>
  <%= form.submit %>
#配置/路由
...
资源:订单可以
资源:项目
结束
#app/controllers/itesm_controller.rb
类ItemsController
尝试过这个:?