ruby-on-rails - has_many :通过关联,shell 中的 Rails 控制台中的 "No Method Error",NoMethodError:#<ActiveRecord::Relation:> 的未定义方法

标签 ruby-on-rails ruby ruby-on-rails-3 postgresql sorting

我正在开发 Rails 3 应用程序中的一项功能。我有一个新模型,称为 Box,其中有许多“产品”。 has_and_belongs_to_many 给我带来了麻烦。所以我制作了一个名为 BoxProduct 的新模型。它看起来像这样:

    class Box < ActiveRecord::Base
    attr_accessible :name, :product_ids
    has_many :box_products, :class_name => 'BoxProduct'
    has_many :products, through: :box_products
    accepts_nested_attributes_for :box_products
    end


    class BoxProduct < ActiveRecord::Base
    attr_accessible :box, :product
    belongs_to :box
    belongs_to :product
    end

    class Product < ActiveRecord::Base
    include Concerns::Notifiable
    include ThinkingSphinx::Scopes

    attr_accessible :box_ids


    has_many :box_products
    has_many :boxes, through: :box_products
    end

-我在这里遇到的第一个问题是:当我访问 Rails 控制台中的 Box 时:

[1] pry(main)> b = Box.first
Box Load (2.0ms)  SELECT "boxes".* FROM "boxes" LIMIT 1
=> #<Box id: 1, name: "Test", image: nil, ....                        
[2] pry(main)> b.products
Product Load (1.6ms)  SELECT "products".* FROM "products" INNER JOIN
"box_products" ON "products"."id" = "box_products"."product_id"
WHERE "box_products"."box_id" = 1
=> []
[3] pry(main)> b = Box.where("id" => 2)
Box Load (0.8ms)  SELECT "boxes".* FROM "boxes" WHERE   
"boxes"."id" = 2
=> [#<Box id: 2, name: "Yoo", image: "image.jpeg" ....
[4] pry(main)> b.products
NoMethodError: undefined method `products' for # 
<ActiveRecord::Relation:0x007f3b68c30208>
from /home/vagrant/.rbenv/versions/2.1.5/lib/ruby/gems/2.1.0/gems/activerecord-3.2.13/lib/active_record/relation/delegation.rb:45:in `method_missing'

但是,在 CMS 的盒 subview 页面中,@box.products 返回表中每个盒子的产品作为实现,对于我迄今为止创建的所有盒子条目。

最佳答案

您的第一个问题很容易解决:请注意 where 不会从数据库返回单个对象,即使只找到一个条目。 where 返回 ActiveRecord::Relation ,它充当您问题上下文中的列表。

Box.where("id" => 2)
#=> [#<Box id: 2, ... # Note the `[` at the beginning of the line

并且您无法在此 Relation 上调用 products,因为 products 是在 Box 上定义的,而不是在关系

您可以根据需要通过不同的方式解决此问题。

您可以迭代该列表并在每个条目上调用products:

Box.where(id: 2).map(&:products)
Box.where(id: 2).includes(:products)

或者您可以使用仅返回单个元素的方法:

Box.find(2).products
Box.find_by(id: 2).products
Box.where(id: 2).take.products
Box.where(id: 2).first.products

关于ruby-on-rails - has_many :通过关联,shell 中的 Rails 控制台中的 "No Method Error",NoMethodError:#<ActiveRecord::Relation:> 的未定义方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35372033/

相关文章:

ruby-on-rails - 表中列中的字符限制与 Rails 中的验证

ruby-on-rails - rails : Formtastic field with description

ruby - Unicorn Rails - 在生产模式下启动时占用 100% CPU

ruby - 返回匹配为数组的元素

ruby - 在 PostgreSQL 中按指定列分组

javascript - Rails 5 不渲染 JQuery 结果

ruby-on-rails - Ruby on Rails : "couldn' t find file 'jquery-ui' "

ruby - Watir - 在方法之外记录

ruby-on-rails - Cucumber Capybara 按 id、名称或标签以外的方式查找复选框

javascript - Rails 3 中的表单和表单验证 : build your own vs Formtastic vs SimpleForm vs other gems?