0
votes

I am new to ruby with rails,I generated a new Controller named users by using command:

rails generate controller users register index login

After that I opened register.html.erb and wrote following code:

<h1>Register New User</h1>
<p>
    <%= form_for :user do |f| %>
    <%= f.label:USERID %><%= f.text_field:userid %><br />
    <%= f.label:PASSWORD %><%= f.text_field:password %><br />
    <%= f.label:EMAIL %><%= f.text_field:email %><br />
    <br />
    <%= f.submit %>
    <% end %>
</p>

Then in users_controller.rb I wrote following code in register:

class UsersController < ApplicationController
  def index
  end

  def show
  end

  def login
  end

  def register
      print "test"
  end

def user_params params.require(:user).permit(:userid,:password,:email) end end

And test is not being printed and get and post methods of the form are not working at all. And params.require(:user).permit(:userid,:password,:email) is not working as well. I get error that :user is empty.

1

1 Answers

0
votes

I get error that :user is empty.

form_for(path/to/your/controller/action) is a helper method to create HTML form elements with the url path to the POST or GET request. The helper knows if it should be a new record or an update record based on what you are asking to do in your controller action. So, basically, it's looking for the @user in the corresponding controller action when you write form_for @user in your view. As you don't have it currently, hence you ar getting this error.

See this for more information.

To solve your current problem, you have to define the @user in the controller's register action:

  def register
     @user = User.new(user_params)
  end

Then, in your register.html.erb file's form, you can use that @user:

<h1>Register New User</h1>
<p>
  <%= form_for @user do |f| %>
      <%= f.label :USERID %>
      <%= f.text_field :userid %><br />
      <%= f.label :PASSWORD %>
      <%= f.text_field :password %><br />
      <%= f.label :EMAIL %>
      <%= f.text_field :email %><br />
      <br />
      <%= f.submit %>
  <% end %>
</p>