Mac
Mac

Reputation: 23

Rails - param is missing or the value is empty - even with matching names

When I use my form to enter data into the database I get this error:

param is missing or the value is empty: application

My controller code is:

def new
  @application = RegisteredApplication.new
end

def create
  @application = RegisteredApplication.new(application_params)

  @application.user = current_user

  if @application.save
    redirect_to @application, notice: "Your new application is now registered"
  else
    flash.now[:alert] = "Error registering application. Please try again."
    render :new
  end
end

private

def application_params
  params.require(:application).permit(:name, :url)
end

The new.html.erb file:

<h1>Register New Application</h1>
<%= render partial: 'form', locals: { application: @application } %>

And the _form.html.erb file:

<%= form_for(application) do |f| %>
    <% if application.errors.any? %>
        <div class="alert alert-danger">
          <h4><%= pluralize(application.errors.count, "error") %>.</h4>
          <ul>
            <% application.errors.full_messages.each do |msg| %>
                <li><%= msg %></li>
            <% end %>
          </ul>
        </div>
    <% end %>
    <div class="form-group">
      <%= f.label :name %>
      <%= f.text_field :name, class: 'form-control', placeholder: "Enter application name" %>
    </div>
    <div class="form-group">
      <%= f.label :url %>
      <%= f.text_field :url, rows: 8, class: 'form-control', placeholder: "Enter application url" %>
    </div>
    <div class="form-group">
      <%= f.submit "Save", class: 'btn btn-success' %>
    </div>
<% end %>

Most people posting this particular question don't match the name in the 'create' method with what's in require(). But, don't all my names match?

For further information, if I remove require(:application) so that it looks like this:

params.permit(:name, :url)

the above allows it to go to the database, however, it doesn't pass the information. It creates a row in the DB, but the fields are nil.

Upvotes: 0

Views: 43

Answers (1)

spickermann
spickermann

Reputation: 107142

Because @application is an instance of RegisteredApplication I am pretty sure that your params would look like this:

{ registered_application: { name : # ...

You can see the format of the parameter hash in your log file.

Therefore your application_params method must look like this:

def application_params
  params.require(:registered_application).permit(:name, :url)
end

Upvotes: 1

Related Questions