Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding created_at DESC functionality in Rails

I have an app with post and comment models. In my index action/view, I am iterating through the post and displaying them from most recently created at to oldest created at. My comments are nested inside my posts so in my post show action/view, I want to iterate though the comments and get them to show from most recently created at to oldest created at. I can only seem to get this to work if i create a method in my post.rb file. I have this:

post.rb:

  def newest_comments
    self.comments.order("created_at DESC")
  end  

In my post show view, I can iterate through the post comments and it works great:

<% @post.newest_comments.each do |comment|
<% end %>

BUT I want to set this functionality in the controller layer, but I can't figure out how. This is what I have in the show action in my posts controller:

  def index
    @posts = Post.all.order("created_at DESC")
  end

  def show
    @comment = Comment.new
    @comments = Comment.all.order("created_at DESC")
  end

And now my updated post show view:

<% @post.comments.each do |comment| %>
<% end %>

The @post var is there because of my before action. So my question is, why do I not have access to this ivar in my post show view by simply calling this in my show view?

like image 980
user2045764 Avatar asked Dec 18 '13 05:12

user2045764


People also ask

What is ORM in ROR?

1.2 Object Relational Mapping Object Relational Mapping, commonly referred to as its abbreviation ORM, is a technique that connects the rich objects of an application to tables in a relational database management system.

Is ActiveRecord an ORM?

ActiveRecord is an ORM. It's a layer of Ruby code that runs between your database and your logic code.

What is Rails ActiveRecord?

Rails Active Records provide an interface and binding between the tables in a relational database and the Ruby program code that manipulates database records. Ruby method names are automatically generated from the field names of database tables.

What is ActiveRecord base?

ActiveRecord::Base indicates that the ActiveRecord class or module has a static inner class called Base that you're extending.


1 Answers

With the updates to Rails you can avoid using the created_at DESC SQL syntax with something like this:

@comments = @post.comments.order(created_at: :desc)

like image 112
Bijan Avatar answered Sep 19 '22 09:09

Bijan