Question

transaction.rb model:

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

ticket.rb model:

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

in the view page i have a nested rails form for multiple entries of 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 %>

When I'm submitting the form, I have the following error:

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

I have attr_accessible :tickets_attributes and accepts_nested_attributes_for :tickets in the transaction model and there's still an error. Also when I add plural to the ticket on line <%= f.fields_for :ticket do |t| %>, the quantity field doesn't display.

Was it helpful?

Solution

Your form f is based off of a Transaction object, which has_many :tickets. I believe you should be using the plural :tickets rather than the singular :ticket in your fields_for.

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

If you always want a new ticket, you may need to do:

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

to ensure that a create form shows up.

OTHER TIPS

total re-edit -- sorry its been a while I had to refresh my memory

transaction.rb tickets_attributes is ok.

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

transaction_controller.rb you must build the tickets.

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

new.rb or in your form, fields_for must be for :tickets as rob as pointed out:

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

  ...

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

I think you might be missing the build part in the controller. hope that helps!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top