开发者

ordering by child's value in one to many relationship

开发者 https://www.devze.com 2023-02-08 12:01 出处:网络
posts table int id comments table int id int post_id datetime created_at i need to orde开发者_如何学运维r posts by post\'s comments created_at. I tried something like that but i can\'t select di

posts table

int id

comments table

int id
int post_id
datetime created_at

i need to orde开发者_如何学运维r posts by post's comments created_at. I tried something like that but i can't select distinct post ids.Any help will be appreciated.

Post.all(:joins => :comments, :order => 'comments.created_at')    

I want to see the post which was commented lately at the top.


The condition you are passing is invalid. The easiest way you can accomplish what you are trying to do, is by adding a column to your posts table - say last_commented_at. In your Comment model you add a callback

class Comment < ActiveRecord::Base
  belongs_to :post

  after_save :update_posts_last_commented_attribute

  def update_posts_last_commented_attribute
    post.update_attribute(:last_commented_at, updated_at)
  end
end

Then you can load your Posts by calling

Post.order("last_commented_at DESC" )

to show the posts first, that have recently been commented.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号