Ajaykumar Ajaykumar - 12 days ago 6
Ruby Question

Get Request is passed instead of post request from new.html

I am trying out for basic login and registration in ruby on rails,
ISSUE: When I click register button from new.html I am getting GET request but I can see method="post" in page source of that html
I have posted my code below
new.html.erb

<form>
<%= form_for(@user) do |f| %>
<%= f.label :user_name %>
<%= f.text_field :user_name %></br>
<%= f.label :email_id %>
<%= f.text_field :email_id %></br>
<%= f.label :password %>
<%= f.password_field :password %></br>
<%= f.label :college %>
<%= f.text_field :college %></br>
<%= f.label :major %>
<%= f.text_field :major %></br>
<%= f.label :current_job %>
<%= f.text_field :current_job %></br>
<%= f.submit("Create Account",class: "btn btn-primary") %>
<% end %>
</form>


My index.html.erb code which is loaded while application starts

<div class="container">
<div class="row">

<div class="login">

<%= form_tag("/user/login",:method => :post) do %>
<%= label_tag(:EmailId) %>
<%= text_field_tag(:email, params[:email]) %></br>
<%= label_tag(:password) %>
<%= password_field_tag(:password, params[:password]) %></br>
<%= submit_tag("Log In",class: "btn btn-primary") %>
<%= submit_tag("Register",class: "btn btn-primary") %>

<% end %>
</div>


</div>
</div>


My controller code

class UsersController < ApplicationController
def index
@user = User.all
end



def login
print "In Sign in controller"
@user = User.new
if params[:commit] == 'Register'
print "inside Register class"
redirect_to '/users/new'
else
@user = User.find(params[:email_id])
if @user and user.authenticate(params[:password])
sessions[:userId] = @user.user_id
end
end
end


def new
puts "****Inside New Method******"
@user = User.new
end

def create
puts "****Inside create Method******"
end
private
def user_params
end

end


My Route code

Rails.application.routes.draw do
root 'users#index'
resources :users
post '/users/login' => 'users#login'


As per my understanding post request should hit create method, but get /users method is hitting. Please help me out regarding this

Answer

You have a form tag inside another form tag. Remove the tag at the top of your form. <%= form_for(@user) %> takes care everything that's needed to build the correct form.