开发者

Correct find syntax for :first, :order in Rails 3?

开发者 https://www.devze.com 2023-02-04 17:49 出处:网络
I am currently using the following to retrieve a town name: place = Town.find(:first, :conditions => [\"name = ?\", par开发者_StackOverflowams[:place_post]])

I am currently using the following to retrieve a town name:

place = Town.find(:first, :conditions => ["name = ?", par开发者_StackOverflowams[:place_post]])
place ||= Town.find(:first, :order => "damlev(`towns`.`name`, '" + params[:place_post] + "')")

What would be the best way to do this, named scopes etc I just feel this is well rubbish and bad practice.

Thanks!


If params[:place_post] is the name of the town:

place = Town.find(:first, :conditions => ["name = ?", params[:place_post]], :order => "name [ASC|DESC]")

Use either ASC or DESC.

Updated with ARel syntax:

place = Town.where(:name => params[:place_post]).order("name [ASC|DESC]").first()

or:

place = Town.order("name [ASC|DESC]").find_by_name(params[:place_post])

Don't know exactly what's the idea with the demlev function, but this may work:

place = Town.order("demlev(name, #{quoted_place_post]}) [ASC|DESC]").find_by_name(params[:place_post])

quoted_place_post can be Town.quote_value(params[:place_post])

0

精彩评论

暂无评论...
验证码 换一张
取 消