ruby on rails - Find a record that belongs to another -
a "user" has_many "foods", 1 food marked "favorite". given user, how can find favorite food or nil
if no favorite food exists?
users table
id, email:string
foods table
id, user_id:integer, name:string, is_favorite:boolean
possible solutions:
i
foods.where()
, fill in criteria user ,is_favorite
field. doesn't seem best activerecord way. see #2.i try find traversing objects, seems better code me:
@favorite_food = current_user.foods.???
i'm not sure how find favorite.
it's important answer returns falsey value , not error if no foods have been listed.
have try following code
@favorite_food = current_user.foods.where(is_favorite: true).first
Comments
Post a Comment