![](/img/trans.png)
[英]NoMethodError: undefined method `user' for has_many :through Association
[英]has_many :through association, “No Method Error” in rails console in shell, NoMethodError: undefined method for #<ActiveRecord::Relation:>
我正在使用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的Box视图页中,@ box.products返回表中每个Box作为产品的产品,作为我到目前为止创建的所有Box条目的产品。
您的第一个问题很容易解决:请注意,即使只找到一个条目, where
也不会从数据库返回单个对象。 where
返回一个ActiveRecord :: Relation ,它充当问题上下文中的列表。
Box.where("id" => 2)
#=> [#<Box id: 2, ... # Note the `[` at the beginning of the line
而且您不能在此Relation
上调用products
,因为products
是在Box
上定义的,而不是在Relation
上定义的。
您可以根据需要以不同的方式解决此问题。
您可以遍历该列表并在每个条目上调用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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.