Show Author and Time Error?
I have this method on the article page which show the article author and timestamp and it works fine in view/articles/show.html.erb. But when I put the same method on the index page under /views/articles/_article.html.erb I keep getting this error - it works in one page display but not the other. Any suggestions?
'The error:'
NoMethodError in Articles#index
Showing /Users/blog/app/views/articles/_article.html.erb where line #13 raised:
undefined method `User' for nil:NilClass开发者_JAVA技巧
Extracted source (around line #13):
11:
12: <div class="post_by">
13: Posted by <%= @article.user.'username' %> on <%= @article.created_at.strftime("%B %d, %Y") %>
14: </div>
15:
Trace of template inclusion: app/views/articles/index.html.erb
Rails.root: /Users/blog
Application Trace | Framework Trace | Full Trace
app/views/articles/_article.html.erb:13:in `_app_views_articles__article_html_erb__997953145_2197490260_6874828'
app/views/articles/index.html.erb:15:in `_app_views_articles_index_html_erb___514612748_2197511860_0'
app/controllers/articles_controller.rb:11:in `index'
It's expecting an @article object to be present, and you're probably not initializing one in your index method. For example, "show" defines it:
def show
@article = Article.find(params[:id])
end
But make sure your index method also has something similar, if indeed you need an article object to be loaded
def index
@articles = Article.all
@article = Article.find(params[:id])
end
Now, I don't know what your goal is with the index page, but you would have pass in a specific ID from somewhere in order to load the article object in "index". Therefore, this is a somewhat contrived example.
A common use case to instantiate an object in your "index" method would be if you have the "New Article" form on the index page itself and it needed an empty Article object to work off of. E.g.:
def index
@articles = Article.all
@article = Article.new
end
For one thing, it's not
<%= @article.user.'username' %>
but
<%= @article.user.username %>
Can you show a bit more of your controller where you are initializing @user?
Update: Based on more information given in the comment below. The error message was not on "User" but "user". As such the solution was to use the "article" object provided by the _article.html.erb partial (most probably invoked as a part of a render partial call from another view).
<%= article.user.username %>
精彩评论