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?
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.
ActiveRecord is an ORM. It's a layer of Ruby code that runs between your database and your logic code.
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.
ActiveRecord::Base indicates that the ActiveRecord class or module has a static inner class called Base that you're extending.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With