ruby on rails - How to connect two tables by using ActiveRecord? -
this question has answer here:
- why can't show restaurant list? 3 answers
(sorry issue duplicated. now, deleted issue.) i'm trying ror active records association. , trying connect 2 tables, restaurants , restaurant_translations. these split multi-language support.
here's definition of 2 tables.
create_table "restaurant_translations", id: false, force: :cascade |t| t.integer "id", limit: 4, default: 0, null: false t.integer "restaurant_id", limit: 4 t.string "restaurantname", limit: 255 t.string "address", limit: 255 t.string "tel", limit: 255 t.text "description", limit: 65535 t.string "lang", limit: 255, default: "", null: false t.datetime "created_at", null: false t.datetime "updated_at", null: false end create_table "restaurants", force: :cascade |t| t.string "restaurant_type", limit: 255 t.string "genre", limit: 255 t.string "url", limit: 255 t.string "fb", limit: 255 t.string "mailaddr", limit: 255 t.datetime "created_at", null: false t.datetime "updated_at", null: false end
and models.
class restaurant < activerecord::base has_many :restaurant_translations end class restauranttranslation < activerecord::base self.table_name = 'restaurant_translations' belongs_to :restaurant end
and here's controller creates headache.
class restaurantcontroller < applicationcontroller def list @restaurants = restaurant.all @restaurants = @restaurants.restaurant_translation.find_by(lang: "en") end end
so error shows this. tell me how write?
@pavan 's advice causes errors this.
btw, view this. it's .slim file.
h1 = t :restraunt_list_title table thead tr th = t :restraunt_list_type th = t :restraunt_list_name th = t :restraunt_list_url th = t :restraunt_list_genre th = t :restraunt_list_addr tbody - @restaurants.each |restaurant| tr td = restaurant.restaurant_type td = restaurant.restaurant_translations.first.restaurantname td = link_to 'here', restaurant.url td = restaurant.genre td = restaurant.restaurant_translations.first.address br
undefined method `restaurant_translation' restaurant::activerecord_relation:0x007f83832cb498
there 2 problems in code
first, calling .restaurant_translation
should .restaurant_translations
per associations.
and second, calling on activerecord_relation collection of records(i.e, @restaurants
) not single instance.
i below instead achieve wanted.
class restaurantcontroller < applicationcontroller def list @restaurants = restaurant.includes(:restaurant_translations).where('restaurant_translations.lang = ?', "en").references(:restaurant_translations) end end
note:
your restaurants
table shouldn't contain restaurant_id
convention.
Comments
Post a Comment