Reputation: 861
I cannot save the data in child model with using accepts_nested_attributes_for
.
Althogh there are many similar questons, they don't work for me.
No error message is displayed when I save the data.
But Unpermitted parameter
is displayed and INSERT
for child model isn't generated in the log.
log
INSERT
for amount
is not generated.
Unpermitted parameter: amount_attributes
(0.2ms) BEGIN
(0.2ms) BEGIN
SQL (3.8ms) INSERT INTO "events" ("start_at", "end_at", "title", "room_id", "created_at", "updated_at") VALUES ($1, $2, $3, $4, $5, $6) RETURNING "id" [["start_at", "2000-01-01 01:00:00.000000"], ["end_at", "2000-01-01 02:00:00.000000"], ["title", "add id parameter"], ["room_id", 38], ["created_at", "2016-06-21 07:31:05.143296"], ["updated_at", "2016-06-21 07:31:05.143296"]]
models
models/rooms.rb
has_many :events, inverse_of: :room, dependent: :destroy
has_many :amounts, inverse_of: :room, dependent: :destroy
accepts_nested_attributes_for :events, allow_destroy: true
models/events.rb
has_one :amount, inverse_of: :schedule, dependent: :destroy
accepts_nested_attributes_for :amount, allow_destroy: true
models/amounts.rb
belongs_to :room, inverse_of: :amounts
belongs_to :event, inverse_of: :amounts
contrller
controllers/events_controller.rb
before_action :load_room
def new
@event = Event.new
@event.room = @room
@event.build_amount
end
def create
@event = Event.new(event_params)
if @event.save
flash[:success] = "event created!"
redirect_to current_user
else
render 'new'
end
end
private
def load_room
@room = Room.find(params[:room_id])
end
def event_params
params.require(:event).permit(
:id, :_destroy, :start_at, :end_at, :title, :detail, :room_id, :category, :ccy, :amount,
amounts_attributes: [
:id, :schedule_id, :room_id, :event_id, :ccy, :amount
]
)
end
view
/views/events/new.html.erb
<%= form_for([@room, @event]) do |f| %>
<%= f.label :title %>
<%= f.text_field :title %>
<%= f.text_field :start_at, :class => 'form-control'%>
<%= f.text_field :end_at, :class => 'form-control'%>
<%= f.fields_for :amount do |a| %>
<%= a.text_field :amount %>
<% end %>
<%= f.hidden_field :room_id %>
<%= f.submit "Post", class: "btn btn-primary" %>
<% end %>
It would be appreciated if you could give me any suggestion.
Upvotes: 0
Views: 181
Reputation: 33542
Unpermitted parameter: amount_attributes
As per your associations, you need to change amounts_attributes
to amount_attributes
in event_params
method.
def event_params
params.require(:event).permit(:id, :_destroy, :start_at, :end_at, :title, :detail, :room_id, :category, :ccy, :amount, amount_attributes: [:id, :schedule_id, :room_id, :event_id, :ccy, :amount])
end
Upvotes: 1