steven_noble
steven_noble

Reputation: 4213

Single Ruby/Rails method to check an object both exists and has an ID

Before I start littering my code with an unwieldy method of my own creation, I'm wondering if there's an existing Ruby/Rails method that will:

I've tried to search the API docs but the terms I'm using are by necessity so general (ID, save, exists, etc) that I've not found anything so far.

Upvotes: 3

Views: 993

Answers (2)

Artem Korneev
Artem Korneev

Reputation: 167

For first 2, use [email protected]_record? new_record? method returns true/false if model was saved to database and have id or not.

For third, read this: defined?

Upvotes: 0

Dogbert
Dogbert

Reputation: 222428

You can use .try

@foo.try(:id)

will return id or nil.

If you strictly want true or false,

[email protected](:id)

Upvotes: 4

Related Questions