【问题标题】:How to create multiple children objects after the parent has been created?创建父对象后如何创建多个子对象?
【发布时间】:2018-05-21 22:58:19
【问题描述】:

这是我的场景:

我有一个 Order 模型和一个 Item 模型。它们有如下关系:

class Order < ApplicationRecord
    has_many :items
end

class Item < ApplicationRecord
    belongs_to :order
end

在我的项目中,最初,我需要创建没有项目的订单。之后我需要创建与该订单相关的项目。

我已经尝试过用户 nested_attributes,但是,我需要多次创建项目,并且在第二次尝试我已经创建的项目显示在表单中进行编辑。

关于最佳方法的任何建议?

编辑:

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

【问题讨论】:

标签: ruby-on-rails ruby forms activerecord nested-attributes


【解决方案1】:

一个选项可能是先创建您的订单,然后再创建项目。

# 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 %>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-14
    • 1970-01-01
    • 2013-04-06
    • 2010-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多