Fra*_*ran 15 activerecord ruby-on-rails
我正在尝试使用通过globalize2转换的字段来订购查询.问题是,由于存储在数据库和协会中,我遇到了很多问题.
category_translations.name不起作用的.with_translationsglobalize2中的定义,但是我得到了一个错误,即使没有订购也无法让它工作.我有类似的东西
class Category < ActiveRecord::Base
validates_presence_of :name
validates_uniqueness_of :name
has_many :products, :dependent => :destroy
translates :name
end
Run Code Online (Sandbox Code Playgroud)
问题是,我如何按翻译名称订购?
reb*_*tte 13
该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
我使用 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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3348 次 |
| 最近记录: |