【问题标题】:Strong params not saved in nested form强参数未以嵌套形式保存
【发布时间】:2017-03-13 01:30:15
【问题描述】:

在我的应用中,我想创建具有nameprice事件 在这些活动中,我希望能够添加参与者,他们有一个first_name和一个salary

我将 gem Cocoon 用于嵌套表单

EventsController 我正在尝试创建我的参与者...

我没有找到正确的方法来做到这一点......

事件控制器

class EventsController < ApplicationController
  def new
    @event = Event.new
    @participant = Participant.new
  end

  def create
    @event = Event.create(params_event)
    if @event.save
      @event.participants.create([{first_name: params[:first_name], salary: params[:salary], event_id: params[:id]}])
      #binding.pry
      redirect_to @event
    end
  end

  def show
    @event = Event.find(params[:id])
  end

  private

  def params_event
    params
      .require(:event).permit(:name,:total_price,
        participants_attributes: [:first_name, :salary, :_destroy ] )
  end
end

我希望我的创建方法像这样在给定事件中呈现一组参与者...

@event.participants.create!([john={first_name: "John", salary: 2000, event_id: params[:id]}, mike={first_name: "Mike", salary: 1400, event_id: params[:id]}])

这是 binding.pry 的结果

 8: def create
     9:   @event = Event.create(params_event)
    10:   if @event.save
    11:   @event.participants.create([{first_name: params[:first_name], salary: params[:salary], event_id: params[:id]}])
    12:   #@event.participants.create!([john={first_name: "John",  salary: 2000, event_id: params[:id]}, mike={first_name: "Mike", salary: 1400, event_id: params[:id]}])
    13:   binding.pry
 => 14:     redirect_to @event
    15:   end
    16: end

[1] pry(#<EventsController>)>
[1] pry(#<EventsController>)> @event
=> #<Event:0x007f89f8013c98
 id: 67,
 name: "Rent a plane",
 total_price: 3400,
 created_at: Mon, 13 Mar 2017 01:18:24 UTC +00:00,
 updated_at: Mon, 13 Mar 2017 01:18:24 UTC +00:00>
[2] pry(#<EventsController>)> @event.participants
  Participant Load (0.2ms)  SELECT "participants".* FROM "participants" WHERE "participants"."event_id" = $1  [["event_id", 67]]
=> [#<Participant:0x007f89f6773580
  id: 30,
  first_name: nil,
  salary: nil,
  created_at: Mon, 13 Mar 2017 01:18:24 UTC +00:00,
  updated_at: Mon, 13 Mar 2017 01:18:24 UTC +00:00,
  event_id: 67>]

如果需要这里是我的模型:

class Event < ApplicationRecord
  has_many :participants, dependent: :destroy
  accepts_nested_attributes_for :participants, reject_if: :all_blank, allow_destroy: true
end

class Participant < ApplicationRecord
  belongs_to :event
end

还有我的表格:

new.html.erb

 <%= simple_form_for @event do |f| %>
          <%= f.input :name, label: "Event's name" %>
          <%= f.input :total_price, label: "What is the total price" %>
          <h2> Add your friends to share the bill</h2>
            <%= f.simple_fields_for :participants do |participant| %>
              <%= render "events/participants_fields", f: participant %>
            <% end %>
            <%= link_to_add_association 'add a friend', f, :participants, partial: "events/participants_fields", class:"btn btn-primary" %>
          <%= f.button :submit %>
    <% end %>

部分:_participants_fields.html.erb

<div class='nested-fields participant-background'>
  <%= f.input :first_name, label: "Enter your friend's first name" %>
  <%= f.input :salary, label: "Enter his/her monthly pay" %>
  <%= link_to_remove_association "Remove this friend", f , class: "btn btn-danger btn-xs" %>
</div>

编辑

这些是我创建与未保存参与者的事件时的日志:(我只保留了@event = Event.new(params_event)

tarted GET "/" for ::1 at 2017-03-13 13:55:20 +0100
  ActiveRecord::SchemaMigration Load (7.0ms)  SELECT "schema_migrations".* FROM "schema_migrations"
Processing by EventsController#new as HTML
  User Load (0.6ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2  [["id", 1], ["LIMIT", 1]]
  Rendering events/new.html.erb within layouts/application
  Rendered events/_participants_fields.html.erb (5.8ms)
  Rendered events/new.html.erb within layouts/application (98.6ms)
  Rendered shared/_navbar.html.erb (2.5ms)
  Rendered shared/_flashes.html.erb (0.4ms)
Completed 200 OK in 408ms (Views: 358.0ms | ActiveRecord: 20.9ms)


Started POST "/events" for ::1 at 2017-03-13 13:55:48 +0100
Processing by EventsController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"mMuWIZe06ofG6DCafY2EPrJouIcF4YzKKJx6Y9ct5XUZNHqIyvFY4l3dqiEnxC5NhQapvSnFDukgblJnHg+14g==", "event"=>{"name"=>"Rent a van", "total_price"=>"390"}, "commit"=>"Create Event"}
  User Load (0.3ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2  [["id", 1], ["LIMIT", 1]]
   (0.1ms)  BEGIN
  SQL (11.9ms)  INSERT INTO "events" ("name", "total_price", "created_at", "updated_at") VALUES ($1, $2, $3, $4) RETURNING "id"  [["name", "Rent a van"], ["total_price", 390], ["created_at", 2017-03-13 12:55:48 UTC], ["updated_at", 2017-03-13 12:55:48 UTC]]
   (6.0ms)  COMMIT
   (0.2ms)  BEGIN
   (0.2ms)  COMMIT
Redirected to http://localhost:3000/events/93
Completed 302 Found in 25ms (ActiveRecord: 18.6ms)


Started GET "/events/93" for ::1 at 2017-03-13 13:55:48 +0100
Processing by EventsController#show as HTML
  Parameters: {"id"=>"93"}
  User Load (0.3ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2  [["id", 1], ["LIMIT", 1]]
  Event Load (0.4ms)  SELECT  "events".* FROM "events" WHERE "events"."id" = $1 LIMIT $2  [["id", 93], ["LIMIT", 1]]
  Rendering events/show.html.erb within layouts/application
  Participant Load (0.5ms)  SELECT "participants".* FROM "participants" WHERE "participants"."event_id" = $1  [["event_id", 93]]
  Rendered events/show.html.erb within layouts/application (3.1ms)
  Rendered shared/_navbar.html.erb (3.3ms)
  Rendered shared/_flashes.html.erb (0.8ms)
Completed 200 OK in 41ms (Views: 34.1ms | ActiveRecord: 1.5ms)

【问题讨论】:

  • 您好,欢迎来到 Stack Overflow。 accepts_nested_attributes 应该使用 @event = Event.create(params_event) 行“Just Work” - 您不需要按照您尝试的方式手动创建参与者。您似乎在permit/require 行中设置了正确的字段名称......所以,您能告诉我们您在执行此操作时观察到什么吗?您是否收到错误消息?您能否查看您的日志文件并告诉我们参数中的内容(以及任何Unpermitted params
  • 谢谢 :) 我已经粘贴了我的日志...我没有错误但没有保存参与者:(

标签: ruby-on-rails ruby-on-rails-5 simple-form strong-parameters


【解决方案1】:

问题出在我的表单中...... Cocoon 需要特殊的 div

<div class="container">
  <div class="col-xs-12">
    <%= simple_form_for @event do |f| %>
      <%= f.input :name, label: "Event's name" %>
      <%= f.input :total_price, label: "What is the total price" %>
      <h2> Add your friends to share the bill</h2>
        <div id="participants">
          <%= f.simple_fields_for :participants do |participant| %>
            <%= render "events/participants_fields", f: participant %>
          <% end %>
        </div>
        <div class="links">
          <%= link_to_add_association 'add a friend', f, :participants, partial: "events/participants_fields", class:"btn btn-primary" %>
        </div>
        <%= f.button :submit %>
    <% end %>
 </div>
</div>

我是这样清理控制器的:

class EventsController < ApplicationController

  def new
    @event = Event.new
  end

  def create
    @event = Event.new(params_event)
    if @event.save
      redirect_to event_path(@event)
    end
  end

  def show
    @event = Event.find(params[:id])
  end

  private

  def params_event
    params
      .require(:event).permit(:name,:total_price, participants_attributes: [:first_name, :salary, :_destroy ] )
  end
end

【讨论】:

  • “Cocoon 需要特殊的 div”哦,这很奇怪(而且有点脆弱):/ 很高兴听到您解决了它 :) 大约一天后,您可以将自己的答案标记为“已接受”答案”,这意味着其他人可以看到您的问题已经解决......这对任何偶然发现相同问题并想知道您是否有解决方案的人都有帮助:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-10-14
  • 2014-08-14
  • 1970-01-01
  • 2015-10-15
  • 1970-01-01
  • 1970-01-01
  • 2016-12-06
相关资源
最近更新 更多