我试图使用一个用globalize2翻译的字段来订购一个查询。问题在于,由于存储在数据库和关联中,所以我遇到了很多问题。
做一个包含翻译和category_translations.name排序的
with_translations,但是我在这里得到了一个错误,即使没有命令也无法让它工作。我有过这样的经历
class Category < ActiveRecord::Base
validates_presence_of :name
validates_uniqueness_of :name
has_many :products, :dependent => :destroy
translates :name
end问题是,我怎样才能按翻译好的名字来点菜?
发布于 2014-10-13 19:40:46
with_translations方法似乎是可行的:
Category.with_translations(I18n.locale).order('category_translations.name')
此外,如果您使用的是PostgreSQL,您可能希望在此基础上添加不区分大小写的顺序:
Category.with_translations(I18n.locale).order("LOWER(category_translations.name) ASC")
这里有更多关于这个的信息:https://github.com/globalize/globalize#scoping-objects-by-those-with-translations
发布于 2010-09-10 22:31:43
我使用sqlite3进行了测试,而且它很有效。
class Category < ActiveRecord::Base
...
named_scope :ordered, lambda {|locale|
{
#:select => "categories.*, categories.name sort_name",
# For MySQL
#:select => "categories.*, IF(category_translations.name IS NULL, categories.name, category_translations.name) sort_name",
# For sqlite3
:select => "categories.*, (CASE WHEN category_translations.name IS NULL THEN categories.name ELSE category_translations.name END) sort_name",
:joins => ActiveRecord::Base.sanitize_sql_array([
"LEFT JOIN category_translations on category_translations.category_id = categories.id AND category_translations.locale = ?", locale]),
:order => "sort_name"
}
}
...
end
Category.ordered(some_locale).all # Returns all records, sorted by translated name发布于 2011-01-28 23:49:50
我假设任何名为Category的模型最多都有数百条记录,如果不是更少的话。也许您可以考虑在获取结果之后,在内存中对结果进行排序。
@categories = Category.all # or whatever else to retrieve what you want
@categories.sort! { |a,b| a.name <=> b.name }不过要小心。如果categories表包含超过数千条记录,这将是个坏主意。
https://stackoverflow.com/questions/3596603
复制相似问题