Ruby on rails Can';t按rails索引排序

Ruby on rails Can';t按rails索引排序,ruby-on-rails,ruby,indexing,Ruby On Rails,Ruby,Indexing,我使用了rails globalize和I18n gem。但现在我无法对我的模型进行排序。你们能帮忙吗 我尝试添加一个新索引,但我对索引并不完全熟悉 Controller.rb def index @foods = Food.all.order(:name) add_breadcrumb "index", foods_path end 模式 create_table "food_translations", force: :cascade do |t| t.integer "foo

我使用了rails globalize和I18n gem。但现在我无法对我的模型进行排序。你们能帮忙吗

我尝试添加一个新索引,但我对索引并不完全熟悉

Controller.rb

def index
  @foods = Food.all.order(:name)

  add_breadcrumb "index", foods_path
end
模式

create_table "food_translations", force: :cascade do |t|
t.integer  "food_id",    null: false
t.string   "locale",     null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string   "name"
t.string   "bio"
end

add_index "food_translations", ["food_id"], name: "index_food_translations_on_food_id", using: :btree
add_index "food_translations", ["locale"], name: "index_food_translations_on_locale", using: :btree
add_index "food_translations", ["name"], name: "index_food_translations_on_name", using: :btree

create_table "foods", force: :cascade do |t|
t.string   "address"
t.string   "phone"
t.datetime "created_at",         null: false
t.datetime "updated_at",         null: false
t.string   "image_file_name"
t.string   "image_content_type"
t.integer  "image_file_size"
t.datetime "image_updated_at"
t.string   "yelp"
t.string   "youtube"
end

是的,你需要加入。如果您没有用于翻译的模型,您可以在查找程序中使用.joins。比如:

   Food.joins('INNER JOIN food_translations ON foods.id=food_translations.food_id')
       .order('food_translations.name').where('food_translations.locale=xxx')

附言:我想知道为什么你没有一个关于“食物id”和“地区”的索引,应该是uniq。在您的情况下,一种食物可以有两种或两种以上相同语言的翻译。

名称
食物翻译
的属性,而不是
食物
的属性。您没有在那里显示任何关系,但您需要以某种方式包括
食品翻译
表,以便能够对
食品翻译进行排序。name
。我明白了。我试图加入(FoodTranslations.name),但语法肯定是错误的。问题是,您应该在问题中包括您的模型类,以及相关关联(例如
属于
)。这是否意味着我必须创建一个新的model.rb?食物翻译是由gem完成的,必须有一些代码将食物翻译表映射到ruby对象中。您还可以包括您使用的宝石的名称,以防有人(不是我)熟悉它以及它的具体功能。但是我可以告诉你,你想加入,在ActiveRecord中加入的最自然的方式是使用associations.food\u translations.locale=xxx?我应该为现场设置什么?params[:locale]?如果已设置,则为“是”。我不知道你的应用程序是如何国际化的。所以应该是这样的。where(['food\u translations.locale=?',params[:locale])还有一件事,你知道为什么在我的主页上。where(['food\u translations.locale=NULL)?很好,是的,你需要设置默认值。