Ruby on rails 为什么rails找不到我的表关系?

Ruby on rails 为什么rails找不到我的表关系?,ruby-on-rails,ruby-on-rails-3.2,Ruby On Rails,Ruby On Rails 3.2,但这并不是: p = Product.find(4).models 不知道有什么区别 以下是我的模式: p = Product.where("title = 'some title'").models 您需要双向定义Model和GsCollector之间的关系。您忘记了模型中的零件: create_table "gs_collectors", :force => true do |t| t.integer "project_id" t.integer "mode

但这并不是:

p = Product.find(4).models
不知道有什么区别

以下是我的模式:

p = Product.where("title = 'some title'").models

您需要双向定义Model和GsCollector之间的关系。您忘记了模型中的零件:

  create_table "gs_collectors", :force => true do |t|
    t.integer  "project_id"
    t.integer  "model_id"
    t.integer  "quantity",   :default => 1
    t.string   "housing",    :default => "Base Unit"
    t.string   "hopper"
    t.string   "controller"
    t.boolean  "overbags",   :default => false
    t.datetime "created_at",                          :null => false
    t.datetime "updated_at",                          :null => false
  end

  create_table "models", :force => true do |t|
    t.string   "title"
    t.integer  "product_id"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.integer  "display"
  end


  create_table "products", :force => true do |t|
    t.string   "title"
    t.datetime "created_at"
    t.datetime "updated_at"
  end
类模型

而真正的问题是,您只能对单个记录执行
.models
<代码>产品。其中
返回多个对象-因此使用
产品。按标题(“标题”)查找。模型

您返回的是一个对象数组,统称为
ActiveRecord::Relation
。这是由于您的
where
搜索词造成的。也许你想要以下的东西:

class Model < ActiveRecord::Base
  belongs_to :product
  has_many :gs_collectors
end

class GsCollector < ActiveRecord::Base
  belongs_to :model
end
其中
返回
产品的列表


find
返回单个
产品

能否提供schema.rb的内容?可能您缺少外键。您的问题是
Product.where()
返回一个数组、多个记录。Rails确实知道在哪个平台上获取所有模型。最好使用
产品。按标题(“标题”)查找。模型
.where
.find
之间的区别在于
。find
总是返回符合条件的第一条记录,这就是为什么它总是直接返回记录的原因
。其中
允许返回多条记录,因此始终返回一个ActiveRecord::Relation,该关系充当包含所有匹配记录的数组。@klump,对,我错了。
p = Product.where("title = 'some title'").models
  create_table "gs_collectors", :force => true do |t|
    t.integer  "project_id"
    t.integer  "model_id"
    t.integer  "quantity",   :default => 1
    t.string   "housing",    :default => "Base Unit"
    t.string   "hopper"
    t.string   "controller"
    t.boolean  "overbags",   :default => false
    t.datetime "created_at",                          :null => false
    t.datetime "updated_at",                          :null => false
  end

  create_table "models", :force => true do |t|
    t.string   "title"
    t.integer  "product_id"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.integer  "display"
  end


  create_table "products", :force => true do |t|
    t.string   "title"
    t.datetime "created_at"
    t.datetime "updated_at"
  end
class Model < ActiveRecord::Base
  belongs_to :product
  has_many :gs_collectors
end

class GsCollector < ActiveRecord::Base
  belongs_to :model
end
p = Product.find_by_title('some title').models