【问题标题】:ActiveRecord has_many through has_many relationActiveRecord has_many 到 has_many 关系
【发布时间】: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


【解决方案1】:

是的,它似乎无法确定 post_id 的关联是什么。我会尝试明确说明这一点,例如:

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

【讨论】:

  • 好主意,但不幸的是它没有奏效。现在我得到:ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR: missing FROM-clause entry for table "twitter_posts" LINE 1: ...cial_media_post_id = social_media_posts.id)) AND ("twitter_p... ^ : 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 ("twitter_posts"."post_id" IS NOT NULL)
猜你喜欢
  • 2015-07-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-19
  • 1970-01-01
相关资源
最近更新 更多