undefined method `name' for nil:NilClass while the object exist
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}
I'm creating a blog using ruby on rails and while I'm coding the comments views and I got strange error, which I could not find a solution for
I'm tring to read user name from comment.user and it return this erorr
undefined method `name' for nil:NilClass
If I did inspect the user object, I see the data inside
<%= comment.user.inspect %>
I added the associations between the models correctly
User model
class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_many :comments, dependent: :destroy
end
Post model
class Post < ApplicationRecord
belongs_to :user
has_many :comments, dependent: :destroy
end
Comment model
class Comment < ApplicationRecord
belongs_to :user
belongs_to :post
end
comment View
<strong><%= comment.user.name %>:</strong><%= comment.body %><br><br>
Any help please?
Edit 2:
Comments controller code
class CommentsController < ApplicationController
before_action :set_comment, only: [:show, :edit, :update, :destroy]
# GET /comments
# GET /comments.json
def index
@comments = Comment.all
end
# GET /comments/1
# GET /comments/1.json
def show
end
# GET /comments/new
def new
@post = Post.find params[:post_id]
end
# GET /comments/1/edit
def edit
end
# POST /comments
# POST /comments.json
def create
@comment = Comment.new(comment_params)
@post = Post.find params[:post_id]
@comment.user_id = current_user.id
respond_to do |format|
if @comment.save
format.html { redirect_to @post, notice: 'Comment was successfully created.' }
format.json { render :show, status: :created, location: @comment }
else
format.html { render :new }
format.json { render json: @comment.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /comments/1
# PATCH/PUT /comments/1.json
def update
respond_to do |format|
if @comment.update(comment_params)
format.html { redirect_to @comment, notice: 'Comment was successfully updated.' }
format.json { render :show, status: :ok, location: @comment }
else
format.html { render :edit }
format.json { render json: @comment.errors, status: :unprocessable_entity }
end
end
end
# DELETE /comments/1
# DELETE /comments/1.json
def destroy
@comment.destroy
respond_to do |format|
format.html { redirect_to comments_url, notice: 'Comment was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_comment
@comment = Comment.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def comment_params
params.require(:comment).permit(:body, :user_id, :post_id)
end
end
ruby-on-rails
add a comment |
I'm creating a blog using ruby on rails and while I'm coding the comments views and I got strange error, which I could not find a solution for
I'm tring to read user name from comment.user and it return this erorr
undefined method `name' for nil:NilClass
If I did inspect the user object, I see the data inside
<%= comment.user.inspect %>
I added the associations between the models correctly
User model
class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_many :comments, dependent: :destroy
end
Post model
class Post < ApplicationRecord
belongs_to :user
has_many :comments, dependent: :destroy
end
Comment model
class Comment < ApplicationRecord
belongs_to :user
belongs_to :post
end
comment View
<strong><%= comment.user.name %>:</strong><%= comment.body %><br><br>
Any help please?
Edit 2:
Comments controller code
class CommentsController < ApplicationController
before_action :set_comment, only: [:show, :edit, :update, :destroy]
# GET /comments
# GET /comments.json
def index
@comments = Comment.all
end
# GET /comments/1
# GET /comments/1.json
def show
end
# GET /comments/new
def new
@post = Post.find params[:post_id]
end
# GET /comments/1/edit
def edit
end
# POST /comments
# POST /comments.json
def create
@comment = Comment.new(comment_params)
@post = Post.find params[:post_id]
@comment.user_id = current_user.id
respond_to do |format|
if @comment.save
format.html { redirect_to @post, notice: 'Comment was successfully created.' }
format.json { render :show, status: :created, location: @comment }
else
format.html { render :new }
format.json { render json: @comment.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /comments/1
# PATCH/PUT /comments/1.json
def update
respond_to do |format|
if @comment.update(comment_params)
format.html { redirect_to @comment, notice: 'Comment was successfully updated.' }
format.json { render :show, status: :ok, location: @comment }
else
format.html { render :edit }
format.json { render json: @comment.errors, status: :unprocessable_entity }
end
end
end
# DELETE /comments/1
# DELETE /comments/1.json
def destroy
@comment.destroy
respond_to do |format|
format.html { redirect_to comments_url, notice: 'Comment was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_comment
@comment = Comment.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def comment_params
params.require(:comment).permit(:body, :user_id, :post_id)
end
end
ruby-on-rails
add a comment |
I'm creating a blog using ruby on rails and while I'm coding the comments views and I got strange error, which I could not find a solution for
I'm tring to read user name from comment.user and it return this erorr
undefined method `name' for nil:NilClass
If I did inspect the user object, I see the data inside
<%= comment.user.inspect %>
I added the associations between the models correctly
User model
class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_many :comments, dependent: :destroy
end
Post model
class Post < ApplicationRecord
belongs_to :user
has_many :comments, dependent: :destroy
end
Comment model
class Comment < ApplicationRecord
belongs_to :user
belongs_to :post
end
comment View
<strong><%= comment.user.name %>:</strong><%= comment.body %><br><br>
Any help please?
Edit 2:
Comments controller code
class CommentsController < ApplicationController
before_action :set_comment, only: [:show, :edit, :update, :destroy]
# GET /comments
# GET /comments.json
def index
@comments = Comment.all
end
# GET /comments/1
# GET /comments/1.json
def show
end
# GET /comments/new
def new
@post = Post.find params[:post_id]
end
# GET /comments/1/edit
def edit
end
# POST /comments
# POST /comments.json
def create
@comment = Comment.new(comment_params)
@post = Post.find params[:post_id]
@comment.user_id = current_user.id
respond_to do |format|
if @comment.save
format.html { redirect_to @post, notice: 'Comment was successfully created.' }
format.json { render :show, status: :created, location: @comment }
else
format.html { render :new }
format.json { render json: @comment.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /comments/1
# PATCH/PUT /comments/1.json
def update
respond_to do |format|
if @comment.update(comment_params)
format.html { redirect_to @comment, notice: 'Comment was successfully updated.' }
format.json { render :show, status: :ok, location: @comment }
else
format.html { render :edit }
format.json { render json: @comment.errors, status: :unprocessable_entity }
end
end
end
# DELETE /comments/1
# DELETE /comments/1.json
def destroy
@comment.destroy
respond_to do |format|
format.html { redirect_to comments_url, notice: 'Comment was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_comment
@comment = Comment.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def comment_params
params.require(:comment).permit(:body, :user_id, :post_id)
end
end
ruby-on-rails
I'm creating a blog using ruby on rails and while I'm coding the comments views and I got strange error, which I could not find a solution for
I'm tring to read user name from comment.user and it return this erorr
undefined method `name' for nil:NilClass
If I did inspect the user object, I see the data inside
<%= comment.user.inspect %>
I added the associations between the models correctly
User model
class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_many :comments, dependent: :destroy
end
Post model
class Post < ApplicationRecord
belongs_to :user
has_many :comments, dependent: :destroy
end
Comment model
class Comment < ApplicationRecord
belongs_to :user
belongs_to :post
end
comment View
<strong><%= comment.user.name %>:</strong><%= comment.body %><br><br>
Any help please?
Edit 2:
Comments controller code
class CommentsController < ApplicationController
before_action :set_comment, only: [:show, :edit, :update, :destroy]
# GET /comments
# GET /comments.json
def index
@comments = Comment.all
end
# GET /comments/1
# GET /comments/1.json
def show
end
# GET /comments/new
def new
@post = Post.find params[:post_id]
end
# GET /comments/1/edit
def edit
end
# POST /comments
# POST /comments.json
def create
@comment = Comment.new(comment_params)
@post = Post.find params[:post_id]
@comment.user_id = current_user.id
respond_to do |format|
if @comment.save
format.html { redirect_to @post, notice: 'Comment was successfully created.' }
format.json { render :show, status: :created, location: @comment }
else
format.html { render :new }
format.json { render json: @comment.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /comments/1
# PATCH/PUT /comments/1.json
def update
respond_to do |format|
if @comment.update(comment_params)
format.html { redirect_to @comment, notice: 'Comment was successfully updated.' }
format.json { render :show, status: :ok, location: @comment }
else
format.html { render :edit }
format.json { render json: @comment.errors, status: :unprocessable_entity }
end
end
end
# DELETE /comments/1
# DELETE /comments/1.json
def destroy
@comment.destroy
respond_to do |format|
format.html { redirect_to comments_url, notice: 'Comment was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_comment
@comment = Comment.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def comment_params
params.require(:comment).permit(:body, :user_id, :post_id)
end
end
ruby-on-rails
ruby-on-rails
edited Nov 23 '18 at 13:33
FDI
asked Nov 23 '18 at 13:11
FDIFDI
2981318
2981318
add a comment |
add a comment |
3 Answers
3
active
oldest
votes
Can you try?
<%= comment.user.name if comment.user %>
it works, can you please explain why?
– FDI
Nov 23 '18 at 13:17
Cannot be guaranteed if any of the comment has user...
– Bhojendra Rauniyar
Nov 23 '18 at 13:21
Try in the console to find if there's any :)Comment.where(user: nil)
– Bhojendra Rauniyar
Nov 23 '18 at 13:26
it return empty #<ActiveRecord::Relation >
– FDI
Nov 23 '18 at 13:29
but I notice that the partial view loop 4 times while I have 3 comments in a post
– FDI
Nov 23 '18 at 13:30
|
show 2 more comments
try this <%= comment.user.try(:name) %>
.
It's possible that some comment doesn't contain user value.
it works too, I checked all comments from the console and all comments have a user_id, why does it happen, can you please explain?
– FDI
Nov 23 '18 at 13:19
1
Please check, surely some user_id is not available in User model it self.
– Hardik Upadhyay
Nov 23 '18 at 13:20
Prefer Ruby's safe navigation over try,comment.user&.name
.
– Marcin Kołodziej
Nov 23 '18 at 13:20
add a comment |
try
method is defined on Object class and NilClass class in Rails and it's not part of Ruby itself. You can use try
when you are dealing with potential nil objects.
<%= comment.user.try(:name) %>.
When you use try
in your case, NoMethodError exception will not be raised and nil will be returned instead of the receiving object is a nil object or NilClass.
For more info, you can look up this link
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53447379%2fundefined-method-name-for-nilnilclass-while-the-object-exist%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
3 Answers
3
active
oldest
votes
3 Answers
3
active
oldest
votes
active
oldest
votes
active
oldest
votes
Can you try?
<%= comment.user.name if comment.user %>
it works, can you please explain why?
– FDI
Nov 23 '18 at 13:17
Cannot be guaranteed if any of the comment has user...
– Bhojendra Rauniyar
Nov 23 '18 at 13:21
Try in the console to find if there's any :)Comment.where(user: nil)
– Bhojendra Rauniyar
Nov 23 '18 at 13:26
it return empty #<ActiveRecord::Relation >
– FDI
Nov 23 '18 at 13:29
but I notice that the partial view loop 4 times while I have 3 comments in a post
– FDI
Nov 23 '18 at 13:30
|
show 2 more comments
Can you try?
<%= comment.user.name if comment.user %>
it works, can you please explain why?
– FDI
Nov 23 '18 at 13:17
Cannot be guaranteed if any of the comment has user...
– Bhojendra Rauniyar
Nov 23 '18 at 13:21
Try in the console to find if there's any :)Comment.where(user: nil)
– Bhojendra Rauniyar
Nov 23 '18 at 13:26
it return empty #<ActiveRecord::Relation >
– FDI
Nov 23 '18 at 13:29
but I notice that the partial view loop 4 times while I have 3 comments in a post
– FDI
Nov 23 '18 at 13:30
|
show 2 more comments
Can you try?
<%= comment.user.name if comment.user %>
Can you try?
<%= comment.user.name if comment.user %>
answered Nov 23 '18 at 13:15
Bhojendra RauniyarBhojendra Rauniyar
53k2082135
53k2082135
it works, can you please explain why?
– FDI
Nov 23 '18 at 13:17
Cannot be guaranteed if any of the comment has user...
– Bhojendra Rauniyar
Nov 23 '18 at 13:21
Try in the console to find if there's any :)Comment.where(user: nil)
– Bhojendra Rauniyar
Nov 23 '18 at 13:26
it return empty #<ActiveRecord::Relation >
– FDI
Nov 23 '18 at 13:29
but I notice that the partial view loop 4 times while I have 3 comments in a post
– FDI
Nov 23 '18 at 13:30
|
show 2 more comments
it works, can you please explain why?
– FDI
Nov 23 '18 at 13:17
Cannot be guaranteed if any of the comment has user...
– Bhojendra Rauniyar
Nov 23 '18 at 13:21
Try in the console to find if there's any :)Comment.where(user: nil)
– Bhojendra Rauniyar
Nov 23 '18 at 13:26
it return empty #<ActiveRecord::Relation >
– FDI
Nov 23 '18 at 13:29
but I notice that the partial view loop 4 times while I have 3 comments in a post
– FDI
Nov 23 '18 at 13:30
it works, can you please explain why?
– FDI
Nov 23 '18 at 13:17
it works, can you please explain why?
– FDI
Nov 23 '18 at 13:17
Cannot be guaranteed if any of the comment has user...
– Bhojendra Rauniyar
Nov 23 '18 at 13:21
Cannot be guaranteed if any of the comment has user...
– Bhojendra Rauniyar
Nov 23 '18 at 13:21
Try in the console to find if there's any :)
Comment.where(user: nil)
– Bhojendra Rauniyar
Nov 23 '18 at 13:26
Try in the console to find if there's any :)
Comment.where(user: nil)
– Bhojendra Rauniyar
Nov 23 '18 at 13:26
it return empty #<ActiveRecord::Relation >
– FDI
Nov 23 '18 at 13:29
it return empty #<ActiveRecord::Relation >
– FDI
Nov 23 '18 at 13:29
but I notice that the partial view loop 4 times while I have 3 comments in a post
– FDI
Nov 23 '18 at 13:30
but I notice that the partial view loop 4 times while I have 3 comments in a post
– FDI
Nov 23 '18 at 13:30
|
show 2 more comments
try this <%= comment.user.try(:name) %>
.
It's possible that some comment doesn't contain user value.
it works too, I checked all comments from the console and all comments have a user_id, why does it happen, can you please explain?
– FDI
Nov 23 '18 at 13:19
1
Please check, surely some user_id is not available in User model it self.
– Hardik Upadhyay
Nov 23 '18 at 13:20
Prefer Ruby's safe navigation over try,comment.user&.name
.
– Marcin Kołodziej
Nov 23 '18 at 13:20
add a comment |
try this <%= comment.user.try(:name) %>
.
It's possible that some comment doesn't contain user value.
it works too, I checked all comments from the console and all comments have a user_id, why does it happen, can you please explain?
– FDI
Nov 23 '18 at 13:19
1
Please check, surely some user_id is not available in User model it self.
– Hardik Upadhyay
Nov 23 '18 at 13:20
Prefer Ruby's safe navigation over try,comment.user&.name
.
– Marcin Kołodziej
Nov 23 '18 at 13:20
add a comment |
try this <%= comment.user.try(:name) %>
.
It's possible that some comment doesn't contain user value.
try this <%= comment.user.try(:name) %>
.
It's possible that some comment doesn't contain user value.
answered Nov 23 '18 at 13:15
Hardik UpadhyayHardik Upadhyay
1,8981922
1,8981922
it works too, I checked all comments from the console and all comments have a user_id, why does it happen, can you please explain?
– FDI
Nov 23 '18 at 13:19
1
Please check, surely some user_id is not available in User model it self.
– Hardik Upadhyay
Nov 23 '18 at 13:20
Prefer Ruby's safe navigation over try,comment.user&.name
.
– Marcin Kołodziej
Nov 23 '18 at 13:20
add a comment |
it works too, I checked all comments from the console and all comments have a user_id, why does it happen, can you please explain?
– FDI
Nov 23 '18 at 13:19
1
Please check, surely some user_id is not available in User model it self.
– Hardik Upadhyay
Nov 23 '18 at 13:20
Prefer Ruby's safe navigation over try,comment.user&.name
.
– Marcin Kołodziej
Nov 23 '18 at 13:20
it works too, I checked all comments from the console and all comments have a user_id, why does it happen, can you please explain?
– FDI
Nov 23 '18 at 13:19
it works too, I checked all comments from the console and all comments have a user_id, why does it happen, can you please explain?
– FDI
Nov 23 '18 at 13:19
1
1
Please check, surely some user_id is not available in User model it self.
– Hardik Upadhyay
Nov 23 '18 at 13:20
Please check, surely some user_id is not available in User model it self.
– Hardik Upadhyay
Nov 23 '18 at 13:20
Prefer Ruby's safe navigation over try,
comment.user&.name
.– Marcin Kołodziej
Nov 23 '18 at 13:20
Prefer Ruby's safe navigation over try,
comment.user&.name
.– Marcin Kołodziej
Nov 23 '18 at 13:20
add a comment |
try
method is defined on Object class and NilClass class in Rails and it's not part of Ruby itself. You can use try
when you are dealing with potential nil objects.
<%= comment.user.try(:name) %>.
When you use try
in your case, NoMethodError exception will not be raised and nil will be returned instead of the receiving object is a nil object or NilClass.
For more info, you can look up this link
add a comment |
try
method is defined on Object class and NilClass class in Rails and it's not part of Ruby itself. You can use try
when you are dealing with potential nil objects.
<%= comment.user.try(:name) %>.
When you use try
in your case, NoMethodError exception will not be raised and nil will be returned instead of the receiving object is a nil object or NilClass.
For more info, you can look up this link
add a comment |
try
method is defined on Object class and NilClass class in Rails and it's not part of Ruby itself. You can use try
when you are dealing with potential nil objects.
<%= comment.user.try(:name) %>.
When you use try
in your case, NoMethodError exception will not be raised and nil will be returned instead of the receiving object is a nil object or NilClass.
For more info, you can look up this link
try
method is defined on Object class and NilClass class in Rails and it's not part of Ruby itself. You can use try
when you are dealing with potential nil objects.
<%= comment.user.try(:name) %>.
When you use try
in your case, NoMethodError exception will not be raised and nil will be returned instead of the receiving object is a nil object or NilClass.
For more info, you can look up this link
answered Nov 23 '18 at 16:17
John BakerJohn Baker
1,073411
1,073411
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53447379%2fundefined-method-name-for-nilnilclass-while-the-object-exist%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown