0

In my app I want to create events that have nameand price In these events I want to be able to add participants they have a first_nameand a salary

I am using the gem Cocoon for the nested forms

From the EventsController I am trying to create my participants...

I don't manage to get the right way to do this...

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

I want that my create methode render an array of participants in the given event like this...

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

Here is the result of 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>]

If neeeded here are my models:

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

And my forms:

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

partial: _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>

EDIT

These are my logs when I create an event with participants they aren't saved: ( I just kept the @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)
2
  • Hi and welcome to Stack Overflow. accepts_nested_attributes should "Just Work" with the line @event = Event.create(params_event) - you shouldn't need to be manually creating your participants the way you are trying to do. You seem to have the correct field-names set up in your permit/require line... so, can you tell us what you are observing when you do just this? Are you getting error messages? Can you look in your logfile and tell us what is coming through in params (and any Unpermitted params? Commented Mar 13, 2017 at 4:06
  • Thank you :) I've pasted my logs... I 've no error but no participants saved :( Commented Mar 13, 2017 at 13:01

1 Answer 1

1

The problem was in my forms.... Cocoon needs special 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>

I cleaned the controller like so:

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
Sign up to request clarification or add additional context in comments.

1 Comment

"Cocoon needs special div" ooh that's weird (and a little bit brittle) :/ Good to hear you solved it :) After a day or so, you can mark your own answer as the "accepted answer", which will mean that other people can see that your problem has been solved... it's helpful to anybody else that stumbles across the same problem and is wondering if you have a solution or not :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.