How can I pass multiple attributes to find_or_create_by in Rails 3?

后端 未结 5 1145
独厮守ぢ
独厮守ぢ 2020-12-12 20:53

I want to use find_or_create_by, but this statement does NOT work. It does not \"find\" or \"create\" with the other attributes.

productproperty = ProductPro         


        
5条回答
  •  甜味超标
    2020-12-12 21:22

    In Rails 4, you can use find_or_create_by(attr1: 1, attr2: 2) to find or create by multiple attributes.

    You can also do something like:

    User.create_with(
      password: 'secret', 
      password_confirmation: 'secret',
      confirmation_date: DateTime.now
    ).find_or_create_by(
      email: 'admin@domain.com',
      admin: true
    )
    

    If you need to create the user with some attributes, but cannot search by those attributes.

提交回复
热议问题