Rails find_or_create_by more than one attribute?

后端 未结 5 802
广开言路
广开言路 2020-11-27 09:27

There is a handy dynamic attribute in active-record called find_or_create_by:

Model.find_or_create_by_(: => \"\")

5条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-27 10:11

    You can do:

    User.find_or_create_by(first_name: 'Penélope', last_name: 'Lopez')
    User.where(first_name: 'Penélope', last_name: 'Lopez').first_or_create
    

    Or to just initialize:

    User.find_or_initialize_by(first_name: 'Penélope', last_name: 'Lopez')
    User.where(first_name: 'Penélope', last_name: 'Lopez').first_or_initialize
    

提交回复
热议问题