Search code examples
ruby-on-railsruby-on-rails-4simple-form

How should I use nested attributes with simple_form, Rails 4, and has_many?


I'm trying to use simple_form to create an object and one of its has_many associations with Rails 4.

Here's what I have so far:

class User < ActiveRecord::Base
  has_many :applications
  accepts_nested_attributes_for :applications
end

class Application < ActiveRecord::Base
  belongs_to :user

  def self.allowed_params
      [:over_18]
  end
end

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

  def create
    @user = User.new user_params
    @user.save
    # there is more in here, but I don't think it's relevant
  end

  private
  def user_params
    params.require(:user).permit(:name, :email, application: Application.allowed_params)
  end
end

And finally the form itself

<%= simple_form_for @user do |f| %>
  <%= f.input :name %>
  <%= f.simple_fields_for :application do |a| %>
    <%= a.input :over_18, label: 'Are you over 18?', as: :radio_buttons %>
  <% end %>
  <%= f.button :submit %>
<% end %>

Whenever I try to create a new user with this setup I get an error: ActiveRecord::UnknownAttributeError: unknown attribute 'application' for User.

Question: What should I change so I can create new users with a nested application?

I've tried changing f.simple_fields_for :application to f.simple_fields_for :applications but then simple_fields didn't render the form elements.


Solution

  • A couple of changes should fix your issue:

    1. Ensure @user object has an application instance built before the form is rendered.
    2. Ensure you use form_builder.simple_fields_for :applications, i.e. plural applications as your association is has_many.

    Changes to your Users Controller:

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

    Changes to your view:

    <%= f.simple_fields_for :applications do |a| %>
      <%= a.input :over_18, label: 'Are you over 18?', as: :radio_buttons %>
    <% end %>