Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/62.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 如何从子级访问父级数据_Ruby On Rails - Fatal编程技术网

Ruby on rails 如何从子级访问父级数据

Ruby on rails 如何从子级访问父级数据,ruby-on-rails,Ruby On Rails,当我尝试访问父数据时,得到一个零错误 型号 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 < Appl

当我尝试访问父数据时,得到一个零错误

型号

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
回答


数据完整性问题。在bean_装运中具有与coop表中的行不对应的coop_id。

您确定存在id为
4
的coop吗?-请确认
Coop.find(4)
在rails控制台中返回coops记录。数据完整性问题;coop_id列中有一个4,但coop中没有匹配的行。谢谢
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
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