鉴于我有这个......
create_table "competitors", :force => true do |t|
t.integer "review_id"
end
create_table "questions", :force => true do |t|
t.integer "product_id"
end
create_table "reviews", :force => true do |t|
t.integer "product_id"
end
class Competitor < ActiveRecord::Base
belongs_to :review
def product
self.review.product
end
def questions
self.review.product.questions
end
end
class Review < ActiveRecord::Base
belongs_to :product
def questions
self.product.questions
end
end
class Product < ActiveRecord::Base
has_many :questions
has_many :reviews
end
class Question < ActiveRecord::Base
belongs_to :product
end
......那怎么可能呢?
> @competitor.questions
=> []
> @competitor
=> #<Competitor id: 14, review_id: 7, name: "Colonial FirstState", url: "http://firststate.com.au", created_at: "2013-06-07 06:05:37", updated_at: "2013-06-07 06:05:37", logo_file_name: nil, logo_content_type: nil, logo_file_size: nil, logo_updated_at: nil, logo_processing: false, logo: nil>
> @review = @competitor.review
=> #<Review id: 7, product_id: 9, client_name: "BHP", url: "http://bhp.com.au", created_at: "2013-06-07 06:05:37", updated_at: "2013-06-07 06:05:37">
> @product = @competitor.review.product
=> #<Product id: 9, name: "Retail Site Search", created_at: "2013-06-07 05:54:31", updated_at: "2013-06-07 05:54:31", description: nil>
> @competitor.product
=> #<Product id: 9, name: "Retail Site Search", created_at: "2013-06-07 06:05:37", updated_at: "2013-06-07 06:05:37", description: nil>
> @product.questions
=> []
> Product.find(9).questions
Product Load (1.0ms) SELECT "products".* FROM "products" WHERE "products"."id" = $1 LIMIT 1 [["id", 9]]
Question Load (0.3ms) SELECT "questions".* FROM "questions" WHERE "questions"."product_id" = 9
=> [#<Question id: 13... etc etc ....>]
换句话说,当我通过它的ID找到产品时,我可以看到产品的问题,但是当我在链的末尾找到产品时,我看不到它们。
答案 0 :(得分:0)
如果您没有定义自己的questions
方法,而是使用has_many :questions, through: :product
,那将会好得多。有关详细信息,请参阅http://guides.rubyonrails.org/association_basics.html#the-has_many-through-association。
答案 1 :(得分:0)