Reputation: 1
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
Upvotes: 0
Views: 127
Reputation: 15992
Did you try using order
?:
Artical.includes(:attachments).order('attachments.created_at DESC')
Upvotes: 1
Reputation: 80041
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
end
Artical.order(assoc_updated_at: :desc)
Upvotes: 0