c.nj
c.nj

Reputation: 35

Create action not being called in form

I've just started a new app where I want to take a postcode in a form and save it to the database. My problem is that the create action doesn't seem to be being called no matter what I try.

Routes:

root 'postcodes#new'
resources :postcodes, only: [:new ,:create]

Controller: postcodes_controller.rb

class PostcodesController < ApplicationController
  def new
    @postcode = Postcode.new
  end

  def create
    @postcode = Postcode.new(postcode_params)
    if @postcode.save
      flash[:success] = 'Success'
    else
      flash[:error] = 'Error'
    end
  end

  private

  def postcode_params
    params.require(:postcode).permit(:code)
  end
end

Model: postcode.rb

class Postcode < ApplicationRecord
  validates :code, presence: true, uniqueness: true
end

View: postcodes/new.haml

.container
  %form
    %fieldset.form-group
      = form_for @postcode do |f|
          = f.label :postcode
          = f.text_field :code, placeholder: 'Example Postcode', class: 'form-control'
        = f.submit 'Submit', class: 'btn btn-primary'

I've attempted to pass more options in the form_for such as the method and action and now I have a feeling it's a routing error.

Any help will be appreciated.

Thanks.

Upvotes: 0

Views: 188

Answers (1)

craig.kaminsky
craig.kaminsky

Reputation: 5598

I believe the problem you are experiencing is a result of your HAML.

You do not need to use, nor should you use, a form HTML element outside the form_for method call.

The form_for method will handle generating this HTML element/tag for you.

You have:

.container
  %form
    %fieldset.form-group
      = form_for @postcode do |f|
          = f.label :postcode
          = f.text_field :code, placeholder: 'Example Postcode', class: 'form-control'
        = f.submit 'Submit', class: 'btn ban-primary'

Which outputs an empty <form> element.

You should have:

.container        
  = form_for @postcode do |f|
   %fieldset.form-group  
     = f.label :postcode
     = f.text_field :code, placeholder: 'Example Postcode', class: 'form-control'
    = f.submit 'Submit', class: 'btn ban-primary'

That should generate a proper <form> tag with the required action and method attributes populated with the right URL and 'post' so that your create action is called.

Upvotes: 1

Related Questions