Reputation: 10400
I followed the "Getting Started" tutorial at http://guides.rubyonrails.org/getting_started.html, and wanted to change what is output on the articles index page.
rather than showing the text of the article in the main table, I want to see the most recent comment made on that article.
Here is the code for the index:
<tr>
<td><%= article.title %></td>
<td><%= article.comments.select(:body).last %></td>
<td><%= link_to 'Show', article_path(article) %></td>
<td><%= link_to 'Edit', edit_article_path(article) %></td>
<td><%= link_to 'Destroy', article_path(article),
method: :delete,
data: { confirm: 'Are you sure?' } %></td>
</tr>
Where 'article.comments.select(:body).last' is meant to show the body of the latest comment made on the article in question (this table iterates for every article).
Instead of seeing the text from the comment however, I see this:
I also tried editing comment.create in the comments_controller with:
@article.text = @comment.body
After setting the index table field to 'article.text' (which works fine), but with no effect.
Anyone have any idea what I'm doing wrong?? Any help is much appreciated.
Upvotes: 0
Views: 32
Reputation: 8295
article.comments.select(:body).last
does not do what you expect
the select
part uses this select which alters the SQL command you use. It forces selecting only the body
field from comments and returns a comment object.
so you need to change your code to article.comments.select(:body).last.body
If you need to have all the body
fields and just use one, I suggest that you use pluck if you are on rails > 3.2
article.comments.pluck(:body).last
Upvotes: 2