Question

I have an if statement in my update action in one of my controllers. It looks like this:

if !@bid.attributes.values.include?(nil)
    build(@bid.id)
end

I am checking to see if there are any nil valued attributes in my Bid object before building a bid report. I know the build method works fine because it builds a report when not wrapped in the if statement. When it is wrapped in this if statement, it doesn't run. I have checked to make sure that there are no nil values in the object. I went into the rails console and all attributes have non-nil values. In addition, I am able to check this in the views to confirm that there are no nil values.

I have also tried writing as:

build(@bid.id) unless @bid.attributes.values.include?(nil)

and a couple other variations. None are allowing the build to run.

Was it helpful?

Solution

Your code seems fine, I'm betting it's your data that's the problem instead. Mostly likely, assuming this an active record instance, the attribute is id which will be nil until the new record gets saved.

What do you get in the terminal when you add this line right before your if?

puts @bid.attributes.to_yaml

You should be able to see what has values and what does not. And I'm pretty sure at least one of those values is nil.


I would recommend being more explicit about exactly which fields are required. And this is exactly what validations are for.

class Person < ActiveRecord::Base
  validates :name, presence: true
end

You explicitly validate each field so that when it's absent you get a very specific error message about why: "Person name can't be blank." So instead of wondering why it wont save, you get told why at the point it fails to save.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top