I assume your models look like this:
class User < ActiveRecord::Base has_many :reviews end class Review < ActiveRecord::Base belongs_to :user belongs_to :reviewable, polymorphic: true end class Shop < ActiveRecord::Base has_many :reviews, as: :reviewable end
You cannot complete this request for several reasons.
- ActiveRecord cannot create a connection without additional information.
- There is no table called overview
To solve this problem, you need to explicitly define the relationship between Review and Shop .
class Review < ActiveRecord::Base belongs_to :user belongs_to :reviewable, polymorphic: true # For Rails < 4 belongs_to :shop, foreign_key: 'reviewable_id', conditions: "reviews.reviewable_type = 'Shop'" # For Rails >= 4 belongs_to :shop, -> { where(reviews: {reviewable_type: 'Shop'}) }, foreign_key: 'reviewable_id' # Ensure review.shop returns nil unless review.reviewable_type == "Shop" def shop return unless reviewable_type == "Shop" super end end
Then you can request the following:
Review.includes(:shop).where(shops: {shop_type: 'cafe'})
Note that the table name is shops , not reviewable . There should not be a table in the database that can be viewed in the database.
I find this easier and more flexible than directly defining a join between Review and Shop , as it allows you to get the load in addition to querying related fields.
The reason why this is necessary is because ActiveRecord cannot create a connection based on just considered ones, since several tables represent the other end of the connection, and SQL, as far as I know, does not allow you to join the table named value stored in column. belongs_to :shop defining an additional belongs_to :shop association, you provide ActiveRecord with the information necessary to complete the connection.
Sean Hill Apr 20 '13 at 19:28 2013-04-20 19:28
source share