JeffO
JeffO

Reputation: 137

How to access parent data from child

I'm getting a nil error when I try to access parent data.

Model

class Coop < ApplicationRecord
   has_many :coop_farms
   has_many :farms, through: :coop_farms
   has_many :bean_shipments, inverse_of: :coop
   accepts_nested_attributes_for :bean_shipments
end

class BeanShipment < ApplicationRecord
  belongs_to :coop
  belongs_to :location
  has_many :batch_bean_shipments
  has_many :batches, through: :batch_bean_shipments
  accepts_nested_attributes_for :batch_bean_shipments
end

Controller

class BeanShipmentsController < ApplicationController
  before_action :set_bean_shipment, only: [:show, :edit, :update, :destroy]

  # GET /bean_shipments
  # GET /bean_shipments.json
  def index
    @bean_shipments = BeanShipment.all
    @bean_shipments.each do |bean_shipment|
        puts "Coop_ID is #{bean_shipment.coop_id}"
        puts bean_shipment.coop.name
     end
  end

Output is "COOP_ID is 4" then "undefined method `name' for nil:NilClass"

I don't know how to get the coop.name if I have a valid coop_id?. What am I missing?

edit: Here is schema:

create_table "bean_shipments", force: :cascade do |t|
    t.integer "coop_id", null: false
    t.string "coop_lotcode", null: false
    t.integer "location_id"
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
  end

create_table "coops", force: :cascade do |t|
    t.string "name", null: false
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
  end

Upvotes: 0

Views: 189

Answers (1)

JeffO
JeffO

Reputation: 137

Answered.

Data integrity issue. Had coop_id in bean_shipments that didn't correspond to row in the coop table.

Upvotes: 0

Related Questions