为什么不能显示餐馆名单?
我正在尝试做一些餐馆名单。 我关联了两个表,然后编写此代码。
class Restaurant < ActiveRecord::Base has_many :restaurant_translations end class RestaurantTranslation < ActiveRecord::Base self.table_name = 'restaurant_translations' end
restaurant_controller.rb
class RestaurantController < ApplicationController def list @restaurants = Restaurant.all logger.debug @restaurants end end
list.html.slim table thead tr th Type th Name of Url th Genre th Addr
tbody - @restaurants.each do |restaurant| tr td = restaurant.restaurant_type td = restaurant.restaurant_translations.restaurantname td = link_to 'here', restaurant.url td = restaurant.genre td = restaurant.restaurant_translations.address
但结果低于。 “未定义的方法`restaurantname’为#”
我该怎么办这个问题? 提前致谢。
您的餐厅有多个’restaurant_translations’。
例如,首先你可以写td = restaurant.restaurant_translations.first.try(:restaurantname)
更换
td = restaurant.restaurant_translations.restaurantname
同
td = restaurant.restaurant_translations.first.restaurantname
这会对你有所帮助
因为Restaurent has_many:restaurant_translations所以你需要循环
restaurant.restaurant_translations.each do|res_trans| your code here end