Michael Lee
Michael Lee

Reputation: 458

Object not saving to database

I am trying to create a new object in rails using form_for. For some reason I am unable to get the object to save to the database. See below

model:

class Property < ActiveRecord::Base
  has_many :units
end

view: new.html.erb

<form>
  <div class="form-group">
    <div class = "row">
      <div class="col-md-8">

        <%= form_for (@property) do |f| %>

          <%= f.label :property_name %>
          <%= f.text_field :property_name, class: 'form-control', placeholder:"Please enter property name here" %><br/>

          <%= f.label :property_address %>
          <%= f.text_field :property_address, class: 'form-control' %><br/>
      </div> 
    </div>    
  </div> 
  <%= f.submit "Add Building"%> 
  <% end %>
</form>

controller:

  def new
    @property = Property.new
  end

  def create
    @property = Property.new(property_params)
    if @property.save
      flash[:success] = "Property created"
      redirect_to root_path
    else
      flash[:error] = "Property was not created"
      render new_property_path
    end
  end
private
    def property_params
      params.require(:property).permit(:property_name, :property_address)
    end

Here is the params it produces

Parameters: {"utf8"=>"✓", "authenticity_token"=>"VNad0+BD6TAavWiSCSX12Ob6ilU+DrzDv0O/d++af1+s6BtQkC2hKUUINaPXhk1hWA5Qfa6JV0RwkpAlx8IwKg==", "property"=>{"property_name"=>"test 934", "property_address"=>""}, "commit"=>"Add Building"}

Upvotes: 0

Views: 57

Answers (1)

Mirza Memic
Mirza Memic

Reputation: 872

It seems that you have an extra FORM tag inside your view. Forms cannot be nested in HTML. Inside your view you should remove this form

<form>
  <div class="form-group">
..
..
</form>

This block will generate form with action and method set. So if you remove this extra from it should work.

<%= form_for (@property) do |f| %> 

will generate form method='post' action='/properties'

Hope it helps

Upvotes: 1

Related Questions