undefined method `id' for nil:NilClass when creating a new record

I am having two tables "Journeys" and "stop" When i create a new journey i need to create one stop. The stop is also referencing stations table.This works fine:

@stop = Stop.create(Station.find_by("Station name ").id)

But when i try the below, its giving me a

undefined method `id' for nil:NilClass error

name = "whatever" 
@stop = Stop.create(Station.find_by(name: name).id)

Upvotes: 1

Views: 189

Answers (3)

sreejithgp
sreejithgp

Reputation: 21

Simple there is no name entry "whatever" in stations table.

Stop.create(Station.find_by(name: name)&.id)

If you want to ignore the error and return nil

Upvotes: 0

justapilgrim
justapilgrim

Reputation: 6882

Unlike find, find_by takes a hash parameter, so you should use it like:

Model.find_by(field: "value")

It's giving you this error because there's no record on the database with the given name. You could also try find_by!, that raises a ActiveRecord::RecordNotFound exception when the record doesn't exist.

Upvotes: 1

lacostenycoder
lacostenycoder

Reputation: 11236

How can we be sure find_by name returns a Station object? We can't. This would be safer

if station = Stating.find_by(name: name) # returns nil if no record with name
  @stop = Stop.create(station.id)
end

Upvotes: 0

Related Questions