anonymous2203
anonymous2203

Reputation: 5

Rails unable to insert data into database

I am trying to insert data into Subscriber from index action of labs controller. This is my code.

View HTML:

<div class="container">
  <form id="login">
    <div class="subscribe">
         <%= form_for @subscriber, :url => url_for(:controller => "subscribers", :action => "create" ), remote: true do |f| %>
            <%= f.label :name, 'SUBSCRIBE TO OUR NEWSLETTER' %>&nbsp;&nbsp;&nbsp;
                    <div id="subscribe-text">
            <%= f.email_field :email_address,placeholder: "email address",row:"3", :class => 'email_class' %>&nbsp;&nbsp;&nbsp;
          </div>
        <%= f.submit "Subscribe", :class => 'button_class' %>
              <% end %>
      </form>
      </div>

            </div>

Main Controller

class LabsController < ApplicationController
  layout "labs"
  def index
    @subscriber = Subscriber.new
  end
end

Subscriber Controller

class SubscribersController < ApplicationController

  def create
    @subscriber=Subscriber.new(subscriber_params)
    if @subscriber.save
      redirect_to root_path, notice: "Subscribed Successfully !"
    else
      redirect_to root_path, notice: "Subscription Failed !"
    end
  end

private
  def subscriber_params
    params.require(:subscriber).permit(:email_address)
  end
end

routes.rb

Rails.application.routes.draw do
  resources :subscribers
  root 'labs#index'
  get "home", :to => "labs#index"
end

Output in the console

Started GET "/home?subscriber%5Bemail_address%5D=ss%40w&commit=Subscribe" for 127.0.0.1 at 2018-06-06 23:19:57 +0530
Processing by LabsController#index as HTML
  Parameters: {"subscriber"=>{"email_address"=>"ss@w"}, "commit"=>"Subscribe"}
  Rendering labs/index.html.erb within layouts/labs
  Rendered labs/index.html.erb within layouts/labs (1.6ms)
Completed 200 OK in 19ms (Views: 18.0ms | ActiveRecord: 0.0ms)

Upvotes: 0

Views: 92

Answers (1)

Sovalina
Sovalina

Reputation: 5609

Don't wrap the form_for inside a <form></form> markup. When you hit "Submit" it returns a simple GET request for the markup not the form_for rails helper (which is disabled).

<div class="container">
  <%= form_for @subscriber, url: url_for(controller: "subscribers", action: "create" ), remote: true, html: { id: 'login' } do |f| %>
    <%= f.label :name, 'SUBSCRIBE TO OUR NEWSLETTER' %>&nbsp;&nbsp;&nbsp;
    <div id="subscribe-text">
      <%= f.email_field :email_address, placeholder: "email address",row: "3", class: 'email_class' %>&nbsp;&nbsp;&nbsp;
    </div>
    <%= f.submit "Subscribe", class: 'button_class' %>
  <% end %>
</div>

Upvotes: 1

Related Questions