尝试访问父数据时出现nil错误。
模型
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
控制器
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
输出为“ COOP_ID为4” 然后“为nil:NilClass定义的方法'name'”
如果我有有效的coop.name
,我不知道如何获得coop_id
?我想念什么?
编辑: 这是模式:
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
答案 0 :(得分:0)
回答
数据完整性问题。在bean_shipments中有coop_id与coop表中的行不对应。