Find the newest record in Rails 3
Given a Post model, you could do @post = Post.order("created_at").last
(The reason I didn't just do a @post = Post.last
is because that always defaults to sort by your primary key (usually id
). Most of the time this is fine, but I'm sure there's a scenario where that could cause problems (e.g. setting custom IDs on records, database changes which affect the primary key sequencing/autonumbering, etc.). Sorting by the created_at
timestamp ensures you are really getting the most recent record).
Find last created_at record
That's a valid request
Record.order(created_at: :desc).first
take care of a tree index on this field to have a better performance, though
SQL query to get last record based on table relation
you can do this query (Result here)
with x as (
select row_number() over (partition by p.id order by b.created_at desc) as rn,b.id as id_box,p.id as id_paper
from boxes b join stones s on b.stone_id = s.id
join papers p on p.id = s.paper_id)
select x.id_box from x where rn = 1
ActiveRecord return the newest record per user (unique)
I've found one solution that is suboptimal performance-wise but will work for very small datasets, when time is short or it's a hobby project:
Card.all.order(:user_id, :created_at).to_a.uniq(&:user_id)
This takes the AR:Relation results, casts them into a Ruby Array, then performs a Array#uniq on the results with a Proc. After some brief testing it appears #uniq will preserve order, so as long as everything is in order before using uniq you should be good.
The feature is time sensitive so I'm going to use this for now, but I will be looking at something in raw SQL following @Gene's response and link.
How to get last N records with activerecord?
Updated Answer (2020)
You can get last N records simply by using last method:
Record.last(N)
Example:
User.last(5)
Returns 5 users in descending order by their id.
Deprecated (Old Answer)
An active record query like this I think would get you what you want ('Something' is the model name):
Something.find(:all, :order => "id desc", :limit => 5).reverse
edit: As noted in the comments, another way:
result = Something.find(:all, :order => "id desc", :limit => 5)
while !result.empty?
puts result.pop
end
How to get the latest record from each group in ActiveRecord?
Postgres
In Postgres, this can be achieved with the following query.
SELECT DISTINCT ON ("group") * FROM projects
ORDER BY "group", date DESC, id DESC
Because the date
column might not be unique here, I have added an additional ORDER BY
clause on id DESC
to break ties in favor of the record with the higher ID, in case two records in a group have the same date. You might instead want to use another column like the date/time of the last update or so, that depends on your use case.
Moving on, ActiveRecord unfortunately has no API for DISTINCT ON
, but we can still use plain SQL with select
:
Project.select('DISTINCT ON ("group") *').order(:group, date: :desc, id: :desc)
or if you prefer using ARel instead of having raw SQL:
p = Project.arel_table
Project.find_by_sql(
p.project(p[Arel.star])
.distinct_on(p[:group])
.order(p[:group], p[:date].desc, p[:id].desc)
)
MySQL
For other databases like MySQL this is unfortunately not as convenient. There are a variety of solutions available, see for example this answer.
Include only the latest/newest associated record with active record?
This is a working scope with lambda to pass parameters to the scope to select the genre id.
scope :latest_with_genre, lambda do |searched_genre_id|
joins(:books)
.where('books.date_of_publication = (SELECT MAX(books.date_of_publication) FROM books WHERE books.author_id = authors.id)')
.where("books.genre_id = #{searched_genre_id}").group('author.id')
end
This answer Rails query through association limited to most recent record? from
Pan Thomakos helped me for the scope.
This answer Pass arguments in scope from keymone helped me for passing argument
When creating a new record in Rails 3 get the value of field in previous record
Try using @last_note = @customer.stickies.last.notes
before creating a new record and use this value to show last note.
Related Topics
How to Create a Sha1 Hash in Ruby
How to Get Ruby/Homebrew/Rvm to Work on Yosemite
How to Display Ruby on Rails Form Validation Error Messages One At a Time
Difference Between Ruby and Ruby on Rails
How to Use Define_Method to Create Class Methods
Nokogiri Gem Installation Error
String Interpolation in Ruby Doesn't Work
Ruby Regular Expression to Match a Url
How to Clear the Terminal in Ruby
How to Install Therubyracer Gem on 10.10 Yosemite
Rails Paperclip How to Delete Attachment
Uploading Multiple Files With Paperclip
Reading the Last N Lines of a File in Ruby
How Would You Parse a Url in Ruby to Get the Main Domain
What's This &Block in Ruby? and How Does It Get Passed in a Method Here