Ruby代码报错undefined method `restaurant_id',如何通过用户收藏获取餐厅名?
解决获取收藏餐厅名称时的"undefined method `restaurant_id'"错误
咱们先来拆解下你代码里的问题根源:
你写的get_res_id = customer_favs.each do ... end这里,each方法的返回值是调用它的原数组(也就是customer_favs,一堆Favorite实例),而不是你在块里筛选出来的餐厅。所以后面你试图用get_res_id.restaurant_id时,本质是在给一个数组调用restaurant_id方法,数组根本没有这个方法,自然就报出那个错误了。
修正方案一:不依赖关联,直接通过Favorite获取餐厅名称
如果你暂时没给模型设置关联,可以这样修改代码,用map来收集对应的餐厅实例,再提取名称:
def view_all_favorites(customer) # 遍历用户的收藏,找到对应的餐厅实例,compact去掉可能的nil(比如餐厅已被删除) favorite_restaurants = customer.favorites.map do |fav| Restaurant.find_by(id: fav.restaurant_id) end.compact # 提取所有餐厅名称 restaurant_names = favorite_restaurants.map(&:name) # 友好输出结果 puts "你收藏的餐厅有:#{restaurant_names.join(', ')}" end
修正方案二:利用Active Record关联(更高效简洁)
其实如果给模型设置好关联,代码能简化很多,还能避免重复查询数据库。
先给你的模型加上关联:
# app/models/customer.rb class Customer < ApplicationRecord has_many :favorites has_many :restaurants, through: :favorites # 通过favorites关联到restaurants end # app/models/favorite.rb class Favorite < ApplicationRecord belongs_to :customer belongs_to :restaurant end # app/models/restaurant.rb class Restaurant < ApplicationRecord has_many :favorites has_many :customers, through: :favorites end
之后你的方法就能写成这样,直接通过关联获取收藏的餐厅,并用pluck直接从数据库取名称(比加载整个实例更高效):
def view_all_favorites(customer) restaurant_names = customer.restaurants.pluck(:name) puts "你收藏的餐厅有:#{restaurant_names.join(', ')}" end
核心问题就是你误用了each方法——它是用来遍历执行代码的,不会收集返回结果;要收集处理后的结果,记得用map哦。
内容的提问来源于stack exchange,提问作者hannah
相关产品推荐
相关产品推荐

