通过多态关联查询

时间:2012-11-27 21:15:42

标签: ruby-on-rails polymorphic-associations

只是在玩RoR,尝试通过一些建模找到方法。 请注意以下代码:

 class Picture < ActiveRecord::Base
      belongs_to :imageable, :polymorphic => true
 end

 class Employee < ActiveRecord::Base
      has_many :pictures, :as => :imageable
 end

 class Product < ActiveRecord::Base
      has_many :pictures, :as => :imageable
 end

有没有办法按照特定图片获取产品? 我正在尝试这个,但它不起作用:

picure = Picture.last
product = Product.where(picture: picure)

失败了:

SQLite3::SQLException: no such column: products.picture: SELECT "products".*
FROM "products" WHERE "products"."picture" IS NULL LIMIT 1```

1 个答案:

答案 0 :(得分:0)

如果您有Picture @picture的实例,则可以使用belongs_to将其与Product相关联(假设Picture实际上是Product属于Employee而非product = @picture.imageable

的实例
{{1}}