ActiveRecord has_many通过has_many关系

时间:2016-08-17 23:59:10

标签: sql ruby-on-rails ruby-on-rails-4 activerecord

我有以下型号:

class Company < ActiveRecord::Base
    has_many :social_media_posts
    has_many :twitter_posts, through: :social_media_posts
end

class SocialMediaPost < ActiveRecord::Base
    belongs_to :company
    has_many :twitter_posts, dependent: :destroy
    accepts_nested_attributes_for :twitter_posts
end

class TwitterPost < ActiveRecord::Base
    belongs_to :social_media_post
    has_one :company, through: :social_media_post
end

TwitterPost有一个名为post_id的属性,它是从Twitter的API返回的推文的ID - 而不是关联的Post模型的ID。出于某种原因,当我运行以下代码行时,它会中断:

# company.twitter_posts.where.not(post_id: nil).count
# Expected output:
# => 103

我明白了:

ActiveRecord::StatementInvalid: PG::UndefinedColumn: ERROR:  column "post_id" does not exist
LINE 1: ...cial_media_post_id = social_media_posts.id)) AND (post_id IS...
                                                             ^
: SELECT COUNT(*) FROM "social_media_posts" WHERE "social_media_posts"."company_id" = $1 AND (EXISTS(SELECT 1 FROM twitter_posts WHERE twitter_posts.social_media_post_id = social_media_posts.id)) AND (post_id IS NOT NULL)

显然,它正在post_id表中查找列social_media_posts,其中没有。当我打电话给company.twitter_posts时,我会得到一个SocialMediaPost::ActiveRecord_AssociationRelation关系,当我希望获得TwitterPost::ActiveRecord_AssociationRelation关系时。我怎样才能解决这个问题,最好不要改变架构(虽然我已经考虑过了,因为它尚未在生产中)?

1 个答案:

答案 0 :(得分:0)

看起来它似乎无法弄清楚post_id的意义何在。我试着明确这一点,例如:

 company.twitter_posts.where.not("twitter_posts.post_id" => nil).count