Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I sort a list of ActiveRecords by an attribute length?

I have an object like this:

irb(main):076:0> hints = Hint.where("sentence LIKE ?","%你%")
  Hint Load (4.0ms)  SELECT "hints".* FROM "hints" WHERE (sentence LIKE '%你%')
[
    [0] #<Hint:0x007fb99c6520b8> {
                :id => 214,
          :sentence => "我为你们立下模范,我向你们怎样做,你们也该照样做。",
              :user => nil,
           :learned => nil,
        :created_at => Sun, 06 Jan 2013 18:14:33 UTC +00:00,
        :updated_at => Sun, 06 Jan 2013 18:14:33 UTC +00:00
    },
    [1] #<Hint:0x007fb99c659a70> {
                :id => 229,
          :sentence => "他快要完成地上的传道工作时,曾向耶和华祷告说“我已经使他们使徒认识你的名,以后还要使他们认识”。",
              :user => nil,
           :learned => nil,
        :created_at => Sun, 06 Jan 2013 18:43:23 UTC +00:00,
        :updated_at => Sun, 06 Jan 2013 18:43:23 UTC +00:00
    },
    [2] #<Hint:0x007fb99c659458> {
                :id => 234,
          :sentence => "你的王到你这里来了。",
              :user => nil,
           :learned => nil,
        :created_at => Sun, 06 Jan 2013 18:48:12 UTC +00:00,
        :updated_at => Sun, 06 Jan 2013 18:48:12 UTC +00:00
    }
]
irb(main):077:0> hints.class
ActiveRecord::Relation < Object

How can I sort by sentence length?

My final goal is to make it so that when someone clicks on a Chinese character in a lesson that they will be shown a few of the shortest example sentences available as a hint to the meaning of the character.

I am using PostgreSQL.

like image 813
webmagnets Avatar asked Jan 06 '13 19:01

webmagnets


4 Answers

Sameera207 has the right idea, but giving you the answer as ruby code.

Hint.where("sentence LIKE ?","%你%").order("LENGTH(sentence) ASC")

This will solve your problem

Perhaps you want a method like this;

def shortest_example(word)
  Hint.where("sentence LIKE ?", "%#{word}%").order("LENGTH(sentence) ASC").first
end
like image 157
Matthew Rudy Avatar answered Nov 16 '22 21:11

Matthew Rudy


I think the easy way is to do your sorting from the DB end, as an example in MySQL:

order by LENGTH(sentence) desc

even you could write a scope for this.

Because as I can see, if you are trying to sort it after the DB select, it will be another loop which is unnecessary.

like image 43
sameera207 Avatar answered Nov 16 '22 22:11

sameera207


this sort:

hints = hints.sort { |x,y| x.sentence.length <=> y.sentence.length }

will do the job

like image 4
masterweily Avatar answered Nov 16 '22 23:11

masterweily


Try

hints = Hint.find_by_sql("SELECT * FROM hints WHERE sentence LIKE('%你%') ORDER BY LENGTH(sentence) ASC")
like image 2
jbnunn Avatar answered Nov 16 '22 21:11

jbnunn