EDIT: SOLVED, view the solution in Brian Kunzig's answer+comments.
I've decided to try out Ruby on Rails and have been constantly running into this problem. I was searching around for problems like this but none of the solutions have done the trick for me. It seems that I constantly write a part of code that just isn't correct. So here are some code snippets:
(ignore what the code would be for, it's just to try stuff out)
My controller:
class AuthsController < ApplicationController
def index
@auths=Auth.all
end
def new
@auth=Auth.new
end
def show
@auth=Auth.find(params[:id])
end
end
My index.html.erb:
<div style="margin: 0 auto; width:50%; text-align: center">
<h1>Please authorise your use of this webpage and its database(s).</h1>
<%= form_for :auth, url: auths_path do |f| %>
<% if @auth.errors.any? %> ==> RAILS REPORTS ERROR IN CODE HERE
<div id="error_explanation">
<h2>
<%= pluralize(@auth.errors.count, "error") %> prohibited
this authentification from being saved:
</h2>
<ul>
<% @auth.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<p>
<%= f.label :username %><br>
<%= f.text_field :username %>
</p>
<p>
<%= f.label :password %><br>
<%= f.text_field :password %>
</p>
<p>
<%= f.submit %>
</p>
<% end %>
</div>
So, bottom line. Rails is saying that I cannot use @auth in the form_for block, for example. Or anywhere else for that matter.. It always says that it belongs to NilClass or something like that. It obviously wants me to instantiate it somehow, but isn't it enough to make the method new and put in the line: @auth=Auth.new ?
I'm just confused with this situation because I can't figure out how it's supposed to go. Thanks a lot !
P.S. I'm using <%= form_for :auth, url: auths_path do |f| %>
because it won't accept @auth, that's what the error in the next line is. I have seen solutions to instantiate it "on the go" outside of the controller but I want to do it the way it's supposed to be done.
You should be putting this form in the new.html.erb
file and not the index
. The index
is for listing entries while the new
and create
actions handle POST
requests. You're getting an error because you're trying to list all Auth's when none have been created. Also, you're sending a form via a GET
request if you're using standard rails routing. Use resourceful routing and put this form in your new
view for that controller and it should work.
Routes file should be:
resources :auths
This will provide all the necessary routing automagically. If you type rake routes
after modifying this you will see the newly generated urls and the helpers to them. You will notice it affords the create
and update
actions a POST
/PUT
request while others are GET
.