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.products는 지금까지 만든 모든 상자 항목에 대해 구현 된 테이블의 각 상자에 대한 제품을 반환합니다.
첫 번째 문제는 해결하기 쉽습니다 where
. 항목이 하나만 발견 된 경우에도 데이터베이스에서 하나의 개체를 반환하지 않습니다. 질문 컨텍스트에서 목록 역할을 where
하는 ActiveRecord :: Relation을 반환합니다 .
Box.where("id" => 2)
#=> [#<Box id: 2, ... # Note the `[` at the beginning of the line
는에 정의되어 있지만에 정의되어 있지 않기 때문에 products
이를 호출 할 수 없습니다 .Relation
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
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다