【问题标题】:Why is rails not finding my table relation?为什么rails找不到我的表关系?
【发布时间】:2012-04-24 19:22:31
【问题描述】:
class Product < ActiveRecord::Base
  has_many :models, :dependent => :destroy, :order => 'display, title'

class Model < ActiveRecord::Base
  belongs_to :product

class GsCollector < ActiveRecord::Base
  belongs_to :model

为什么我不能在 GsCollector 的表单中执行以下操作?:

  <p>
    Model:<br />
    <%= collection_select :gs_collector, :model_id, Product.where("title = 'Some Title'").models.all, :id, :title %>
  </p>

我得到错误:

undefined method `models' for #<ActiveRecord::Relation:0x007fef0ac09350>

models方法不应该由关系提供吗?在控制台中,这有效:

p = Product.find(4).models

但这不是:

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

【问题讨论】:

  • 能否提供schema.rb的内容?也许您缺少外键。
  • 您的问题是Product.where() 返回一个数组,几条记录。 Rails 确实知道从哪个位置获取所有模型。最好使用Product.find_by_title("title").models
  • .where.find 的区别在于.find 总是返回符合条件的第一条记录,所以它总是直接返回记录。 .where 允许返回多条记录,因此总是返回一个 ActiveRecord::Relation,它充当包含所有匹配记录的数组。
  • @klump,对,我错了。

标签: ruby-on-rails ruby-on-rails-3.2


【解决方案1】:

您正在返回一个对象数组,统称为ActiveRecord::Relation。这是由于您的 where 搜索词。也许您想要以下内容:

p = Product.find_by_title('some title').models

where 返回Products 的列表

find 返回单个 Product

【讨论】:

    【解决方案2】:

    您需要同时定义 Model 和 GsCollector 之间的关系。您忘记了模型中的部分:

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

    真正的问题是您只能在一条记录上.modelsProduct.where 返回几个 - 所以使用 Product.find_by_title("title").models

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-02-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-13
      相关资源
      最近更新 更多