我试图创建一个表单,在创建该仪式时自动将奖励保存到仪式中。我已尽力遵循指南https://github.com/plataformatec/simple_form/wiki/Nested-Models和http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html,但我一直收到错误
ActiveModel::ForbiddenAttributesError
我的代码如下:
ceremony.rb
class Ceremony < ApplicationRecord
has_many :awards
accepts_nested_attributes_for :awards, allow_destroy: true, reject_if: lambda { |attributes| attributes['kind'].blank?
end
award.rb
class Award < ApplicationRecord
belongs_to :ceremony
end
_form.html.erb
<%= simple_form_for ceremony do |f| %>
<%= f.input :title %>
<% 3.times do Award.new %>
<%= field_set_tag 'Award' do %>
<%= f.simple_fields_for 'awards_attributes[]', award do |g| %>
<%= g.input :title %>
<%= g.input :description %>
<%= g.input :category_id, as: :select, collection: Category.all %>
<% end %>
<% end %>
<% end %>
<% end %>
最后是ceremonies_controller.rb
class CeremoniesController < ApplicationController
def create
ceremony = Ceremony.new(ceremony_params)
handle_create(ceremony)
end
def new
ceremony = Ceremony.new
end
private
def handle_create
def handle_create(ceremony)
if ceremony.save
create_participant_and_awards(ceremony)
redirect_to ceremony,
notice: 'Ceremony successfully created'
else
render :new, error: 'There was an error adding the ceremony'
end
end
def ceremony_params
params.require(:ceremony).permit(:title, awards_attributes: [:title, :description, :category_id, :ceremony_id])
end
当我填写表单并点击提交时,它不会创建任何相关奖励。它们通过参数传递,如下:
Parameters: {"utf8"=>"✓", "authenticity_token"=>"2MdHYpZW4POOx2STvPP8sDh6lAtisy2dJDEuC1FaKMpOHUmwsQnk6GztnrrS8E2FC5ajvuhGCdZr56QgQMQAag==", "ceremony"=>{"title"=>"Test 1", "organisation"=>"test 1", "description"=>"", "closing_time(1i)"=>"2017", "closing_time(2i)"=>"4", "closing_time(3i)"=>"27", "closing_time(4i)"=>"17", "closing_time(5i)"=>"35", "organiser_id"=>"1", "awards_attributes"=>[{"title"=>"test2", "description"=>"test 2", "category_id"=>"1"}, {"title"=>"test 3", "description"=>"test 3", "category_id"=>"3"}, {"title"=>"test 4", "description"=>"test 4", "category_id"=>"2"}]}, "commit"=>"Create Ceremony"}
我知道我需要列出参数的白名单,但据我所知,按照指南进行操作。我不知道如何将我需要的内容列入白名单。任何帮助都非常感谢