Atari2600
Atari2600

Reputation: 1259

Inspect shows record but still get undefined method

I'm creating a report screen, and doing my relationship lookups for the associated data. For some reason I keep getting errors when trying to get an attribute of the relationship, yet .inspect shows the information plain as day.

orders_detail.products_cost.flavor.inspect

outputs

 #<Flavor flavor_id: 13, identifier: "BR", description: "Blue Razz">

however

orders_detail.products_cost.flavor.flavor_id

outputs

undefined method `flavor_id' for nil:NilClass

models

class OrdersDetail < ActiveRecord::Base
    self.table_name = "orders_detail"
    belongs_to :orders_header, foreign_key: 'order_header_id'
    belongs_to :address 
    belongs_to :products_cost
    belongs_to :machine, foreign_key: 'machine_id'
end



class ProductsCost < ActiveRecord::Base
        self.table_name = "products_cost"
        belongs_to :product
        belongs_to :size
        belongs_to :units_of_measure, foreign_key: "uom_id"
        belongs_to :flavor


        validates :product_id, :presence => true
        validates :flavor_id, :presence => true
        validates :size_id, :presence => true
        validates :uom_id, :presence => true

end


class Flavor < ActiveRecord::Base
    has_many :product_costs
end

Upvotes: 0

Views: 57

Answers (1)

Andrey Deineko
Andrey Deineko

Reputation: 52357

As per discussion in comments to question, having that each of below works as expected:

Flavor.first.flavor_id
Flavor.first.attributes

means, that attributes reading is not broken. The only reason is that as per error: you are referencing bad/invalid/inexistent object flavor.

Upvotes: 1

Related Questions