Rails4:accepts_nested_attributes_for 未在子模型中保存数据并显示不允许的参数

Rails4: accepts_nested_attributes_for not saving the data in child model and display Unpermitted parameter

我无法使用 accepts_nested_attributes_for 将数据保存在子模型中。 尽管有很多类似的问题,但它们对我不起作用。

保存数据时没有显示错误信息。 但是显示了 Unpermitted parameter,并且未在日志中生成子模型的 INSERT

log

INSERT for amount 未生成。

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 (, , , , , ) 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/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

控制器

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

查看

/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 %>

如果您能给我任何建议,我们将不胜感激。

Unpermitted parameter: amount_attributes

根据您的联想,您需要在 event_params 方法中将 amounts_attributes 更改为 amount_attributes

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