Ruby on rails Rails 3:按多个字符串排序
我有多个字符串,它们都是数值。它们都在同一个db表中。有没有一种方法可以将它们全部合并并按最大的数目排序 类似于(伪代码): 在MySql中:Ruby on rails Rails 3:按多个字符串排序,ruby-on-rails,sql-order-by,rails-activerecord,Ruby On Rails,Sql Order By,Rails Activerecord,我有多个字符串,它们都是数值。它们都在同一个db表中。有没有一种方法可以将它们全部合并并按最大的数目排序 类似于(伪代码): 在MySql中: Foo.order '(convert(word_one, unsigned) + convert(word_two, unsigned) + convert(word_three, unsigned))' 在ActiveRecord中: Foo.all.sort_by do |f| %w[one
Foo.order '(convert(word_one, unsigned) +
convert(word_two, unsigned) +
convert(word_three, unsigned))'
在ActiveRecord中:
Foo.all.sort_by do |f|
%w[one two three].sum { |n| f.send("word_#{n}").to_i }
end
或者,如果这些字段位于Foo中:
class Foo < ActiveRecord::Base
def self.sorted_by_sum_of_words
order '(convert(word_one, unsigned) +
convert(word_two, unsigned) +
convert(word_three, unsigned))'
end
end
class Foo
然后在控制器中:
class FooController < ApplicationController
def my_action
@foos = Foo.sorted_by_sum_of_words
end
end
class FooController
如果将数字存储在数字列中,则不需要进行转换。在MySql中:
Foo.order '(convert(word_one, unsigned) +
convert(word_two, unsigned) +
convert(word_three, unsigned))'
在ActiveRecord中:
Foo.all.sort_by do |f|
%w[one two three].sum { |n| f.send("word_#{n}").to_i }
end
或者,如果这些字段位于Foo中:
class Foo < ActiveRecord::Base
def self.sorted_by_sum_of_words
order '(convert(word_one, unsigned) +
convert(word_two, unsigned) +
convert(word_three, unsigned))'
end
end
class Foo
然后在控制器中:
class FooController < ApplicationController
def my_action
@foos = Foo.sorted_by_sum_of_words
end
end
class FooController
如果您将数字存储在数字列中,则无需进行转换。您能给我举个例子吗?我很感激!我似乎无法理解控制器操作中的第二个ActiveRecord示例。我的控制器操作如下:@ethos=user.ethosCan您能给我举个例子吗?我很感激!我似乎无法理解控制器操作中的第二个ActiveRecord示例。我的控制器操作如下:@etos=user.ethosw为什么字符串值实际上是数字?@ismaelga我还在学习。我还有很多其他字符串,这些是它们的数值。例如,我得到了:word\u one,:word\u two,:word\u three——这些数字与它们一起使用,而不会在数据库中创建过多的表。为什么字符串值实际上是第一位的数字?@ismaelga我还在学习。我还有很多其他字符串,这些是它们的数值。例如,我得到了:word_one,:word_two,:word_three——这些数字与它们一起使用,而不会在数据库中创建过多的表。