通过嵌套迭代返回实例



对于customer_favs,我能够为与我合作的当前客户保存收藏夹的所有实例。客户的收藏夹包括客户 ID 和餐厅 ID。有了这个,我决定遍历它,并遍历所有餐厅,看看该餐厅实例的 id 是否与收藏夹的restaurant_id相同,并返回它,这给了我一个收藏夹数组。

现在我正在尝试做的是找到一种方法,通过包含restaurant_id的收藏夹返回餐厅的实例,我只想获取餐厅的名称。我决定再次迭代收藏夹数组并遍历餐厅并进行比较以查看收藏夹的restaurant_id是否与餐厅的实例之一相同,并将这些实例保存在变量中,但我收到错误说"未定义的方法'restaurant_id'"。

def view_all_favorites(customer)
customer_favs = customer.favorites
get_res_id = customer_favs.each do |fav_res|
Restaurant.all.select do |res|
res.id == fav_res.restaurant_id
end
end
get_res = Restaurant.all.select do |res|
get_res_id.restaurant_id == res.id
end
puts "#{get_res}"
end

评论中提到的问题很重要,但这里有一个轻微的编辑来让它工作:

def view_all_favorites(customer)
customer_favs = customer.favorites # get favorites from customer
get_res_id = customer_favs.map do |fav_res| # get restaurant IDs from favorites
fav_res.restaurant_id
end
get_res = Restaurant.all.select do |res| # get restaurants from their IDs
get_res_id.include?(res.id)
end
res_names = get_res.map do |res| # get names from restaurants
res.name
end
puts "#{res_names}"
end

这可能可以简化为这样:

def view_all_favorites(customer)
favorite_restaurants = Restaurant.where(id: customer.favorites.map(&:restaurant_id))
puts favorite_restaurants.map(&:name)
end

但是,正如塔德曼所说,最好建立关系,这样你甚至不必这样做。

最新更新