【发布时间】:2016-08-17 23:59:09
【问题描述】:
我有以下型号:
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)
很明显,它正在寻找social_media_posts 表中的post_id 列,但该列没有。当我调用company.twitter_posts 时,我得到一个SocialMediaPost::ActiveRecord_AssociationRelation 关系,而我希望得到一个TwitterPost::ActiveRecord_AssociationRelation 关系。我该如何解决这个问题,最好不更改架构(尽管我会考虑它,因为这还没有投入生产)?
【问题讨论】:
-
我认为这可能是您的数据库架构问题。
标签: sql ruby-on-rails ruby-on-rails-4 activerecord