undefined method `errors' in rails 4
12,966
Solution 1
In your controller:
def new
@post = Post.new
end
and in your View
<%= form_for :post, url: posts_path do |f| %>
<% if @post.errors.any? %>
<div id="errorExplanation">
<h2><%= pluralize(@post.errors.count, "error") %> prohibited
this post from being saved:</h2>
Yes, you simply have to instantiate the Post object....now in your case, Post is not instantiated so that error is thrown. You also should know that errors is defined as an instance method not as a class method. Hence it will be called on a specific instance.
You can find more information on active model errors using the following link:
http://api.rubyonrails.org/classes/ActiveModel/Errors.html
Solution 2
In your controller:
def new
@post = Post.new
end
In your view:
<%= form_for :post, url: posts_path do |f| %>
<% if @post.errors.any? %>
<div id="errorExplanation">
<h2><%= pluralize(@post.errors.count, "error") %> prohibited
this post from being saved:</h2>
Author by
nilkash
Updated on June 24, 2022Comments
-
nilkash almost 2 years
Hi I am beginner to ruby on rails and I am developing small blog application using this ref http://guides.rubyonrails.org/getting_started.html
I am facing following problem here .
<%= form_for :post, url: posts_path do |f| %> <% if @post.errors.any? %> // Error showing undefined errors method <div id="errorExplanation"> <h2><%= pluralize(@post.errors.count, "error") %> prohibited this post from being saved:</h2>
I am beginner to this environment. How to solve this problem. Need help. Thank you.
-
SG 86 over 10 yearsIam guessing that @post is nil. Please post the code with generates @ post
-
Rajarshi Das over 10 years
<% @post ||= Post.new %>
Please add this line into your views -
nilkash over 10 years@rajarshi thank you for solution. But can you please explain how it works.
-
Rajarshi Das over 10 yearsyes it is just instantiate the Post object....now the funda is ||= it will check if the post is exists or not like in edit post already exists for new in your case Post is not instantiate so the error throw .....
-
-
nilkash over 10 yearsbadal can you please explain it more. Thank you for help
-
Admin over 10 years@nilkash Please see Rajarshi answer it is more perfect
-
Mischa over 10 yearsIt's a very bad suggestion to add that in the view. This is typically something that should be done in the controller. You're teaching a beginner the wrong way.
-
Mischa over 10 yearsNo, your answer is better. It's very bad to suggest doing that in the view. @badal
-
Sahil Babbar over 8 yearsBut, what if Post is not a model and has only a controller and a view?
-
Am33d almost 6 yearsany idea how I can do that in haml? I tried but it's not working for me