如何使用唯一ID动态创建嵌套资源?

时间:2014-02-26 06:14:03

标签: ruby-on-rails ruby-on-rails-4 spree

我有一个使用Spree line_item的嵌套表单。我已将票证对象附加到spree_line_item。当我update_attributes时,只捕获了姓氏,因为动态生成的输入id都是相同的。

编辑:根据姓氏,我指的是最后一条记录。因此,如果有2个'first_name'/'last_name'组合,则仅捕获第二个组合。

line_item_decorator.rb

Spree::LineItem.class_eval do
    has_many :tickets, dependent: :destroy
    accepts_nested_attributes_for :tickets
end

ticket.rb

class Ticket < ActiveRecord::Base
    belongs_to :line_item
end

permitted_attributes.rb

permitted_attributes.rb

    module Spree
      module PermittedAttributes
        ATTRIBUTES = [
          ...
          :taxonomy_attributes,
          :ticket_attributes,
          :user_attributes,
          :variant_attributes
        ]

        mattr_reader *ATTRIBUTES

        ...

        @@line_item_attributes = [:id, :variant_id, :quantity, :ticket_attributes]

        ...


        @@ticket_attributes = [:id, :line_item_id, :first_name, :last_name, :start_date, 
        :end_date, :time]

        ...
      end
    end

order_decorator.rb

Spree::Order.class_eval do
    remove_checkout_step :registration
    insert_checkout_step :tickets, :before => :address
end

tickets.html.erb

<table>
  <%= form_for :line_item do |line_item_form| %>
    <% @order.line_items.each do |line_item| %>

      For <%= line_item.start_date %>, provide the names for your <%= line_item.quantity %> <%= line_item.name %> <%= line_item.variant.option_values.first.presentation %> tickets:
      <% (1..line_item.quantity).each do %>
        <%= line_item_form.fields_for :tickets do |ticket_fields| %>
          <tr>
            <td class="line_item_ticket">
              <%= ticket_fields.label :first_name %>
              <%= ticket_fields.text_field :first_name %>
            </td>
            <td class="line_item_ticket">
              <%= ticket_fields.label :last_name %>
              <%= ticket_fields.text_field :last_name %>
            </td>
          </tr>
        <% end -%>
      <% end -%>
    <% end %>
  <% end %>
</table>

0 个答案:

没有答案