Reputation: 2244
Ok so I've got multiple users on my app who each have multiple 'status_updates'.
Each status update is id'd and then has an association for the user it belongs to.
So all the status updates for, say, user 2, might have id's in order 3,10,34,55
The thing is, each status_update needs information from the status update before it for that user. Clearly I can't simply find the status update with id - 1 because that status update may belong to a different user, and will return nil anyways since that status update doesn't exist for the user at hand.
I don't know how to write the where() arguments in order to simply find the previously created status update for the user.
Soo...
Here are the vital parts of my model regarding this question:
after_find :previous_status_update
.
.
.
def previous_status_update
current_id = self.id
previous_status_update = user.status_update.where( created_at: ? < self.created_at ).limit(1)
end
The instructions on guides.rubyonrails.org are confusing when it comes to writing the arguments for this.
Thanks for your help!
Upvotes: 0
Views: 83
Reputation: 6030
This will surely work for you.
previous_status_update = user.status_update.where( created_at: ? < self.created_at ).last
Upvotes: 0
Reputation: 406
You're so close.
previous_status_updates = user.status_update.where("created_at < ?", self.created_at)
This will return all of the status updates that are older than that one.
If you want just the one, just grab the first or last in that list (whichever is the one you want, if you want you can sort it first too with .order()
previous_status_update = user.status_update.where("created_at < ?", self.created_at).first
Upvotes: 2