首页 > 解决方案 > 通过嵌套迭代返回实例

问题描述

对于 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

标签: ruby-on-railsruby

解决方案


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

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

但是,正如 tadman 所说,最好建立关系,这样您甚至不必这样做。


推荐阅读