Whats the right way to avoid this nil error

I have an model Order and a model Customer. Each customer has_many
Orders. Each Order belongs_to a Customer.

If I create an order but don’t specify a Customer (for whatever
reason, maybe it’s unknown at the time)… I obviously can’t access
@order.customer.name because I’ll get a nil error…

So what’s the right way to handle that? If the Customer is nil I just
want to see just that… The blank space in my collection_select
selected… If the customer is nil I’d like my list views to just put
a blank in there…

I know I can do

@order.customer ? @order.customer.name : nil

but I don’t want to do that 100000 times… I know there has to be an
easier way just not exactly what.

Thanks.

On Oct 12, 2007, at 1:05 PM, [email protected] wrote:

@order.customer ? @order.customer.name : nil

If that’s exceptional I use instead what’s called “optimistic” approach:

@order.customer.name rescue nil

but I don’t want to do that 100000 times… I know there has to be an
easier way just not exactly what.

If that value with those semantics is used so much it would be a good
idea to add it to the model:

class Order

 def for
   customer ? customer.name : nil
 end

end

to be able to just say

<%= @order.for %>

I don’t know whether “for” is the best name but you see the idea.

– fxn

Gotcha. Adding a method to the model was how I thought I should be
doing it but I wasn’t sure if the model would know what “customer”
was… I mean, I guess it has to becaues of the association but I’m a
still a little uncertain on the different scopes in ruby.

I think it’s coming together now for me though… I’m looking into it
more and I think I was assuming that
def for
would actually do what
def self.for
does. Which I didnt want. I think I’m cleared up now…

Thanks.

  • FJM

On Oct 12, 2007, at 1:50 PM, [email protected] wrote:

Gotcha. Adding a method to the model was how I thought I should be
doing it but I wasn’t sure if the model would know what “customer”
was… I mean, I guess it has to becaues of the association but I’m a
still a little uncertain on the different scopes in ruby.

I see.

Yes, it is expected that orders know about their customers, and
belongs_to is the succint idiom to declare that relationship.
Furthermore, take into account that models in Rails are not just Ruby
proxies to database tables. Tables store the core attributes of
models, but in the application side you normally add methods to the
ones provided by AR so that the model offers the complete needed
interface for your application.

I think it’s coming together now for me though… I’m looking into it
more and I think I was assuming that
def for
would actually do what
def self.for
does. Which I didnt want. I think I’m cleared up now…

def self.for defines a class methods, def for defines an instance
method. Objects like @order respond to instance methods. You need to
learn Ruby to program in Rails.

– fxn