Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
676 views
in Technique[技术] by (71.8m points)

ruby-on-rails - 如何按属性长度对ActiveRecords列表进行排序?(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?

(如何按sentence长度排序?)

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.

(我正在使用PostgreSQL。)

  ask by webmagnets translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

(Sameera207有一个正确的想法,但是给您答案是红宝石代码。)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...