user1885058
user1885058

Reputation: 599

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")

Upvotes: 2

Views: 5553

Answers (1)

deefour
deefour

Reputation: 35370

Yes, it's called find_or_create_by

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

Upvotes: 7

Related Questions