Ruby on Rails でActiveRecordを使っています。
例えば以下の様な6つのテーブルがあったとして
Area
- AreaTranslation(has many・複数の翻訳された地域情報がある)
- Restaurant(has many・複数の店舗情報がある)
- RestaurantTranslation(has many・複数の翻訳された店舗情報がある)
このような関係性だった場合
Areaテーブルのid=1に紐づくRestaurantTranslationの情報(例:restaurantname)を取得するにはどのようにしたらいいでしょうか?
【追記】
実はErrorが出ていて、
Association named 'restaurant_translations' was not found on Area; perhaps you misspelled it?
となってしまいます。
URLでIDを指定しているので、それに紐付いたrestaurantとrestaurant情報が全部出力したい感じです。
ソースを提示します。Controllerはこちらです。
ruby
1class AreaController < ApplicationController 2 def index 3 @areas = Area.all 4 end 5 6 def show 7 @areas = Area.includes(:area_translations, :restaurants, :restaurant_translations).where(id: params[:id]) 8 end 9end
Modelはこちらです。
ruby
1class Area < ActiveRecord::Base 2 has_many :area_translations 3 has_many :restaurants 4end 5 6class Restaurant < ActiveRecord::Base 7 has_many :restaurant_translations 8 has_many :menus 9 has_many :reviews 10 11 belongs_to :areas 12 13end 14 15class RestaurantTranslation < ActiveRecord::Base 16 self.table_name = 'restaurant_translations' 17 belongs_to :restaurants 18 19 scope :with_lang , -> { where(lang: I18n.locale )} 20 21end 22 23class AreaTranslation < ActiveRecord::Base 24 belongs_to :areas 25 26 scope :with_lang , -> { where(lang: I18n.locale )} 27end 28
View(slim)はこちらです。
ruby
1table 2 thead 3 tr 4 th = t :restaurant_list_type 5 th = t :restaurant_list_name 6 th = t :restaurant_list_url 7 th = t :restaurant_list_genre 8 tbody 9 - @areas.each do |area| 10 tr 11 td = area.restaurants.restaurant_type 12 td = link_to area.restaurants.restaurant_translations.with_lang.first.restaurantname, (url_for controller:'restaurant', trailing_slash: true) + area.restaurants.id.to_s 13 td = link_to 'official', area.restaurants.url 14 td = area.restaurants.genre
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2016/06/24 08:31
2016/06/24 09:42
2016/06/24 12:12
2016/06/24 13:28
2016/06/24 14:53
2016/06/24 15:36
2016/06/24 16:01
2016/06/24 16:17