Rails4:accepts_nested_attributes_for不保存子模型中的数据并显示Unpermitted参数

时间:2016-06-21 08:46:34

标签: ruby-on-rails ruby-on-rails-4 strong-parameters

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

保存数据时不显示错误消息。 但是会显示Unpermitted parameter,并且日志中不会生成子模型的INSERT

登录

INSERT未生成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 ($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"]]

模型

模型/ 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

模型/ events.rb

  has_one :amount, inverse_of: :schedule, dependent: :destroy
  accepts_nested_attributes_for :amount, allow_destroy: true

模型/ amounts.rb

  belongs_to :room, inverse_of: :amounts
  belongs_to :event, inverse_of: :amounts

contrller

控制器/ 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 %>

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

1 个答案:

答案 0 :(得分:1)

  

未经许可的参数:amount_attributes

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

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