将实例添加到迁移模型



我正在尝试将餐厅的实例添加到我的收藏夹模型中,但是我收到一个错误,说"bin/run.rb:441:inadd_favorite_restaurant': undefined methodid' for nil:NilClass (NoMethodError("。在迁移表中,收藏夹的模型由 restaurant.id 和 customer.id 组成,所以我不明白为什么在使用 id 时会出现错误,因为它是必需的......

def add_favorite_restaurant(customer)
puts "What restaurant would you like to add to your favorites?"
favorite_name = gets.chomp
restaurant = Restaurant.find_by(name: favorite_name)
# binding.pry
Favorite.create(
restaurant_id: restaurant.id,
customer_id:   $customer.id
)
puts "You have successfully added #{favorite_name} to your favorites"
end

Ruby 中以$开头的变量是全局变量...几乎永远不应该使用。

所以,很明显,错误undefined method id for nil:NilClass来自这条线......

customer_id: $customer.id

customeradd_favorite_restaurant方法的参数...因此,您只需删除美元符号即可解决问题(假设您传入的参数不nil并且是Customer的实例(...

customer_id: customer.id
customer

作为参数传递,但您使用$customer- 在代码中,一旦数据库中不存在餐厅,命令restaurant = Restaurant.find_by(name: favorite_name)中的餐厅变量可以为 nil

最新更新