Error prevention by empty DB's request

Hi

I have often the problem that rails outputs an error because of requests
from an empty database.

I will check, before showing features on the page, if a flag is set in
the database. The problem is, that the DB is not filled, if you dont add
the flag before. The result if i am doing the request is a nil object.

For example:

if @tourscheduler_user.tourscheduler_id == @tourscheduler.id then
‘bla’
else
‘bla2’
end


The idee is: If there is a entry in @tourscheduler_user with the same id
then do else.

How can i check before if @tourscheduler_user.tourscheduler_id is empty?

Something like != nil ?

Greetings Andi

nil returns false, so

if @tourscheduler_user.tourscheduler_id &&
@tourscheduler_user.tourscheduler_id == @tourscheduler.id then
…id and matching…
else
…no id or not matching…
end

But there are several issues with this approach.

  1. if you use tourscheduler_id, then there should always be a
    tourscheduler matching it
    Otherwise your db is inconsistent. If you delete a tourscheduler you
    should make
    sure, it’s not referenced anymore…

  2. It’s not very rails like
    You should define
    belongs_to :tourscheduler
    in tourscheduler_user model
    and
    has_many :tourscheduler_users
    in tourscheduler model and use the rails methods to handle
    the ralationship.
    Then your code would be simply:

if @tourscheduler_user.tourscheduler then

else

end

hi Thorsten

Thanks a lot for the answere!!!

I follow your two points but the problem is still there.

You have a nil object when you didn’t expect it!
The error occurred while evaluating nil.tourscheduler

Let me explain the idea:

There is Tourscheduler view where you can create trips with serval
informations. In the view can users join the trip and announce that they
come alonge. My solution is an entry with the user_id and the
tourscheduler_id in the tourscheduler_user DB if the user press a button
in the tourpreview.

The result is an empty tourscheduler_user DB till some user join the
trip.

The query I use to decide if the “join button” is shown or not.

Maybee you have a better idea to solve the join issue?

greetings Andi