Brian Lau Brian Lau - 16 days ago 5
Ruby Question

Can't sort by rails index

I used the rails globalize and I18n gem. But now I can't sort my model. Can you guys help?

I tried adding a new index, but I'm not entirely familiar with indexing.

Controller.rb

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

add_breadcrumb "index", foods_path
end


Schema

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

Answer

Yes, you will need a join. If you do not have a model for the translation, you could just use .joins for your finder. Like:

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

ps: I wonder why you do not have a index on "food_id" AND "locale" which should be uniq. In your case you can have two or more translations for 1 food in the same language.