byCoder
byCoder

Reputation: 9184

Ruby on Rails 4 find with order and limit equivalent

I need very fast to update my app controller to rails 4, but i didn't know how to write all this line in new rails 4 style: with order_by with conditions and with limit, in web i search for fast, and all part's together - didn't find. How could i translate this from rails 3 to rails 4?

in controller i have

@news = Article.find(:all, conditions: { text: "example" }, order_by: "created_at", limit: 4 )

i didn't must to use conditions in 4, only where, but how to append :all, order_by and limit to it? What is a right syntax?

Upvotes: 8

Views: 15106

Answers (3)

Matias
Matias

Reputation: 641

I think this might do the trick:

@news = Article.where(text: 'example').order(:created_at).limit(4)

Upvotes: 3

GSP
GSP

Reputation: 3789

In Arel (https://github.com/rails/arel) everything can be appended. The various clauses are described here: http://guides.rubyonrails.org/active_record_querying.html

@news = Article.where(text: 'example').order(:created_at).limit(4)

Note that this returns a query clause that does not actually query the database until you specifically request the data.

Upvotes: 13

DiegoSalazar
DiegoSalazar

Reputation: 13531

From the old ActiveRecord style:

@news = Article.find(:all, conditions: { text: "example" }, order_by: "created_at", limit: 4 )

To the new:

@news = Article.where(text: "example").order(:created_at).limit(4)

Upvotes: 8

Related Questions