Question: order with recent created record in multiple associated models rails


order with recent created record in multiple associated models rails

Answers 2
Added at 2016-12-30 09:12

i have three associated models


 has_many :texts
 has_many :notes
 has_many :attachments

i want to order artical with recent created record

artical 6 = text: 20 dec , note: 19 dec, attachment: 20dec
artical 9 = text: 18 dec , note: 21 dec, attachment: not present 
artical 10 = text: not present , note: 30 dec, attachment: not present

Order will Be depending on text,note,attachment the atrical which has new note,text or attachment will be on the top:

 ###artical Index Page 

 artical 10
 artical 9 
 artical 6

Thanks In Advance

nr: #1 dodano: 2016-12-30 09:12

Did you try using order?:

Artical.includes(:attachments).order('attachments.created_at DESC')
nr: #2 dodano: 2016-12-30 10:12

You have a couple options. One is to join all three associated tables, and use the date functions in your RDBMS (e.g. Postgresql) to determine the latest of the associated created_at dates for each row of the articals table. Depending on your scenario, that might be what you have to do.

If it were me, I'd add a assoc_updated_at column to articals and use the touch in ActiveRecord to bump the timestamp anytime one of the associations was updated, then order by that column:

class Text
  belongs_to :artical, touch: :assoc_updated_at

Artical.order(assoc_updated_at: :desc)
Source Show
◀ Wstecz