Rails中嵌套形式的批量分配错误

时间:2013-04-11 03:43:33

标签: ruby-on-rails-3 nested-forms mass-assignment

transaction.rb型号:

class Transaction < ActiveRecord::Base
  attr_accessible :customer, :tickets_attributes
  has_many :tickets
  accepts_nested_attributes_for :tickets
end

ticket.rb型号:

class Ticket < ActiveRecord::Base
  attr_accessible :booking_id, :quantity, :transaction_id
  belongs_to :transaction
  belongs_to :booking
end

在视图页面中,我有一个嵌套的rails表单,用于ticket的多个条目:

<%= form_for(@transaction) do |f| %>
  <%= f.text_field :customer %>

  <% @sezzion.bookings.each do |booking| %>
      <%= booking.bookingdate %>:

      <%= f.fields_for :ticket do |t| %>
         <%= t.text_field :quantity, :value => 0, :class => "quantity" %>
         <%= t.hidden_field :booking_id, :value => booking.id %>
      <% end %>

  <% end %>
  <%= f.submit "create transaction" %>
<% end %>

当我提交表单时,我有以下错误:

ActiveModel::MassAssignmentSecurity::Error in TransactionsController#create
Can't mass-assign protected attributes: ticket

我在attr_accessible :tickets_attributes模型中有accepts_nested_attributes_for :ticketstransaction,但仍然存在错误。此外,当我在行<%= f.fields_for :ticket do |t| %>上添加复数时,quantity字段不会显示。

2 个答案:

答案 0 :(得分:1)

您的表单f基于Transaction对象,has_many :tickets。我相信您应该在:tickets中使用复数:ticket而不是单数fields_for

  <%= f.fields_for :tickets do |t| %>

如果您总是想要一张新票,您可能需要这样做:

  <%= f.fields_for :tickets, Ticket.new do |t| %>

确保显示创建表单。

答案 1 :(得分:1)

完全重新编辑 - 对不起它已经有一段时间我不得不刷新记忆

transaction.rb tickets_attributes没问题。

class Transaction < ActiveRecord::Base
    attr_accessible :customer, :tickets_attributes
    has_many :tickets
    accepts_nested_attributes_for :tickets
 end

transaction_controller.rb 您必须构建故障单。

def new
    @transaction = Transaction.new
    @transaction.tickets.build
end

new.rb 或在您的表单中,fields_for必须是:tickets,因为我们指出了抢劫:

<%= form_for(@transaction) do |f| %>

  ...

  <%= f.fields_for :tickets do |t| %>
     ...

我想你可能会错过控制器中的build部分。希望有所帮助!