简体   繁体   中英

Create row if it doesn't exist

I need to do something like this:

if @item.exists?(:cron => "mycron")
  # redirect to item page
else
  # create new @item
end

Is there a simpler way to do it in Rails?

Maybe something like:

@item.create_if_not_exists(:cron => "mycron")

Yes, it's called find_or_create_by

@item = Item.find_or_create_by_cron("mycron")
# redirect to item page

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM