2

鉴于我有这个...

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 找到产品时,我可以看到产品的问题,但是当我在链的末端找到产品时,我看不到它们。

4

2 回答 2

0

如果您不定义自己的questions方法,而是使用has_many :questions, through: :product. 有关详细信息,请参阅http://guides.rubyonrails.org/association_basics.html#the-has_many-through-association 。

于 2013-06-07T08:49:41.160 回答
0

答案是委托方法http://api.rubyonrails.org/classes/Module.html#method-i-delegate

于 2013-07-01T03:29:28.103 回答