Nếu bạn nhìn vào các nguồn trong lib/mongoid/finders.rb:
# Find the first +Document+ given the conditions, or creates a
# with the conditions that were supplied.
...
# @param [ Hash ] attrs The attributes to check.
#
# @return [ Document ] A matching or newly created document.
def find_or_create_by(attrs = {}, &block)
find_or(:create, attrs, &block)
end
bạn có thể thấy find_or_create_by chấp nhận một {}
như là đối số đầu tiên. Bạn chỉ có thể chuyển một số điều kiện cùng một lúc
something.find_or_create_by(name: 'john', age: 20)
và nó sẽ hoạt động.
Nguồn
2012-08-16 11:19:05
Cảm ơn bạn rất nhiều! – hyperrjas
Làm cách nào để tìm thấy thuộc tính đầu tiên, và sau đó - chỉ trong trường hợp không tìm thấy gì - hãy tạo các thuộc tính khác? – ChristofferJoergensen
@ChristofferJoergensen, Client.create_with (bị khóa: sai) .find_or_create_by (first_name: 'Andy'), hãy xem các tài liệu: http://guides.rubyonrails.org/active_record_querying.html – mkralla11