22

I'm trying to create one resource with another nested resource at the same time. I'm using Rails4 and simple_form 3.0.0rc. Here is my code.

Models:

class User < ActiveRecord::Base
  has_one :profile
  accepts_nested_attributes_for :profile
end

class Profile < ActiveRecord::Base
  belongs_to :user
end

Controller:

class UsersController < ApplicationController
  def new
    @user = User.new
    @user.build_profile
  end

  def create
    user = User.new user_params
    user.save
    redirect_to root_url
#    @par =params
  end

  private
    def user_params
      params.require(:user).permit(:email, profile_attributes: [:name])
    end
end

View (form for new user)

<%= simple_form_for @user do |f| %>
  <%= f.input :email %>
  <%= simple_fields_for :profile do |p| %>
    <%= p.input :name %>
  <% end %>
  <%= f.submit %>
<% end %>

When I submit the form, the create action receives this params:

{"utf8"=>"✓",
"authenticity_token"=>"dJAcMcdZnrtTXVIeS2cNBwM+S6dZh7EQEALZx09l8fg=", 
"user"=>{"email"=>"[email protected]"},
"profile"=>{"name"=>"Vasily"},
"commit"=>"Create User",
"action"=>"create",
"controller"=>"users"}

And after calling user_params the only thing that left is

{"email"=>"[email protected]"}

And, as you can see, there is nothing about profile, so no profile will be created.

What am I doing wrong?

2 Answers 2

33

Use f.simple_fields_for instead of simple_fields_for:

<%= f.simple_fields_for :profile do |p| %>
    <%= p.input :name %>
<% end %>
Sign up to request clarification or add additional context in comments.

2 Comments

This literally saved me hours.
LOL, I was scratching my head real hard. Thanks. So obvious, don't know why thought it'd be different with simple_form xD
3

In my case I had the object "book" which belongs to "tour" and "tour" has_many "books".

In the "BookController" in the method "new" I find the tour and initialize the book object:

@tour = Tour.find(params[:tour_id])

@book = Book.new

This is the partial form to create a book: _form.html.erb

<%= simple_form_for [@tour, @book] do |f| %>
  <%= f.input :name, label: "Name"%>
  <%= f.input :NoReservations, label: "Number of Reservations" %>
  <%= f.input :email, label: "Email" %>
  <h3>Num of available places</h3>
  <%= f.button :submit %>
<% end %>

Comments

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.