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:

  1. i foods.where() , fill in criteria user , is_favorite field. doesn't seem best activerecord way. see #2.

  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

Popular posts from this blog

apache - Remove .php and add trailing slash in url using htaccess not loading css -

inno setup - TLabel or TNewStaticText - change .Font.Style on Focus like Cursor changes with .Cursor -