Post with latest comment on top of index page - Ruby On Rails - ruby-on-rails

I need to display post with the latest made comment in it, on top of page. And every Post has many comments and many Comments belong to one post.
Here is my index method from Posts controller
def index
#posts = Post.all.order("posts.created_at desc")
def new
#post = Post.new
end
end
I looked through Rails docs and found .order and .where methods, and I think those two methods are the solution to my problem but I am not sure how to use it

try this:
#posts = Post.joins(:comments).order("comments.created_at DESC")

def index
#posts = Post.all.order("created_at DESC")
#latest_post = #posts.first
end
update
I interpreted word comments as posts.
update 2
First you need to find the latest comment:
#latest_comment = Comment.all.order('created_at DESC').first
Having that, you can extract the ID of the Post to which this comment belong:
post_id = latest_comment.post_id
Now you have the latest comment and the respective post's id. I would modify index page like this:
def index
#posts = Post.all.order("created_at DESC")
#latest_comment = Comment.all.order('created_at DESC').first
#post_of_latest_comment = Post.find(#latest_comment.post_id)
end
I am not sure what do you mean by displaying it on top, but I am pretty sure with this code you can do it in your view.
update 3
In your view, you hsould have something like this:
<h1>Top comment</h1>
<%= #latest_comment.text %>
By .textI mean some attribute of model Comment wich contains the content of the comment, plain text. If you need more help with this, show what atributes your Post and Coment model have.

I tried a modified line from Pitabas Prathal:
Post.joins(:comments).order("comments.created_at DESC").group('post_id')
where post_id is the foreign key in the Comment model from the Post model. It worked fine for me :)

Related

Indexing method that gets parameters in Rails 4

I have a store application with a Product scaffold and I want to enable categories and pages that show each category of products.
My product model has a "category" attribute and I use the link_to helper to create links to each category.
In my products controller I added a method called index_by_category(cat):
def index_by_category(cat)
#products_by_category = Product.where(category: cat)
end
I'm trying to iterate #products_by_category in a view I created with the corresponding name (product/index_by_category.html.erb) just like the regular index method do. For some reason it render me the regular index method of products which shows ALL of them, even though the URL is:
http://localhost:3000/products?index_by_category=Food
This is what I did in my route.rb file:
get 'products/index_by_category'
I'm newbie to Rails development so if I did something which is wrong from the roots and the rails approach to the problem should be entirely different I also be happy to know for the sake of learning.
You are doing things a bit wrong. Try to write your controller like this:
def index_by_category
#products_by_category = Product.where(category: params[:category])
end
And update your route
get 'products/category/:category', to: 'products#index_by_category
Then visit
http://localhost:3000/products/category/Food
UPDATE
if you really want to use index method for both cases you could do that by modifying it to something like this
def index
if params[:category]
#products = Product.where(category: params[:category])
else
#products = Product.all
end
end
and then just visit
http://localhost:3000/products?category=Food

How to find a comments' count ... or even articles' count

Ok, relying on guide's blog tutorial:http://edgeguides.rubyonrails.org/getting_started.html
Trying to learn how to write a method myself.
The guide did both article and comments ie, belongs_to & has_many relationship.
So, thought why not try to find out the totality of comments.
This is the method I wrote for Comments controller:
def total_number_of_comments
#article = Article.all
#comments_total = #article.comments.count
end
Then I put this in article's view index.html.erb
<p>Total number of comments:</p>
<%= #comments_total %>
On the index page, it doesn't show anything.
So, what am I doing wrong?
And, I don't want just a "correct" answer. I'd like to understand what I'm missing here.
But what I'm befuddled here is how to think this out.
I hesitate to do this because it would prolong the post, but I thought why not try to do count of articles too.
So, here's what I did:
In Article model
def self.total_number_of_articles
Article.all.count
end
In Article controller
def total_number_of_articles
#articles_total = Article.total_number_of_articles
end
Then in index.html.erb of Article View again, I put this:
<p>Total number of articles:</p>
<%= #total_number_of_articles %>
Again, nothing shows up in terms of count in either comment or article.
So .... clearly I'm missing something here.
EDIT
The comment (total_number_of_comments) method was sorta based on this: (from railsguide)
def create
#article = Article.find(params[:article_id])
#comment = #article.comments.create(comment_params)
redirect_to article_path(#article)
end
There are many things you missed, I would happy to explain you.
Here
def total_number_of_comments
#article = Article.all
#comments_total = #article.comments.count
end
You have to do this
def total_number_of_comments
#comments_total = Comment.all.count // simple solution
end
Next is , you didn't used proper instance variable.
def total_number_of_articles
#articles_total = Article.total_number_of_articles
end
See yourself
Total number of articles:
<%= #total_number_of_articles %> // this is wrong
You assigned #articles_total but used #total_number_of_articles. if you use #articles_total it will work fine.
You should define a function index in your controller.
calling a GET on /articles/index calls the controller function index, you should set #articles_total = Article.total_number_of_articles in your index function in controller. You have it in a function in your controller that is not getting called.

Getting all comments

I have two models: posts and comments. Each comment belongs to a post. I would like to have a page of all comments not just the comments for a post. I can't seem to get this seemingly simple thing to work.
Here is my controller:
def top
#topcomments = #comments.order("created_at desc")
end
I am getting an 'undefined method order' error.
If you want to access comments directly, and not through a relationship with another model, you need to access the model itself, Comment:
def top
#topcomments = Comment.order('created_at desc')
end
how would you get the post for each comment
Assuming you have a relationship set up correctly between comments and posts, you would just access .post for each comment. You can use includes(:post) to avoid the n+1 problem.
def top
#topcomments = Comment.order('created_at desc').includes(:post)
#topcomments.each |comment|
comment.post # here is the post
end
end
def top
#topcomments = Comment.order("created_at desc")
end

How can i make the new post listed at top by moving the previous post down?

I have followed http://guides.rubyonrails.org/getting_started.html and, in that example we can add a new post and it is displayed but the new post is displayed at the bottom when there is a post present already but i wanted to make the new post displayed at the top. How can i do it?
Post.order("created_at desc") will show the most recently created first.
Change
#posts = Post.all
To
#posts = Post.order("created_at DESC")
in your index method of app/controllers/posts_controller.rb
I'd use
#posts = Post.order("id desc")
ID has primary key (by default). The last post will always have max ID
(Unless you update created_at field)

How to get all the Posts from a User

I have a User and Post scaffolded in my rails application. I wanted to get all of the posts associated with a user. For example, I want to be able to do something like this:
localhost:3000/users/1/posts
And it should give me all of the posts with the user_id = 1. I know how to get all the posts via the rails console for a specific user. I was just wondering how i can accomplish something like the example above. Would I have to add another method in the users controller?
You can do it without adding new action. Like this:
class PostsController < ApplicationController
def index
#user = User.find(params[:user_id])
#posts = #user.posts
end
end
another one line example is the following, add this to your index
#posts = User.find(params[:user_id]).posts
I wrote a longish answer to a related question that may be helpful:
https://stackoverflow.com/a/17911920/321583

Resources