3

鉴于以下情况Tweet

# db/schema.rb
create_table "tweets", force: true do |t|
  t.integer  "project_id",            null: false
  t.integer  "author_id",             null: false
  t.integer  "twitter_id",            limit: 8, null: false
  t.text     "text"
  t.integer  "in_reply_to_status_id", limit: 8
  t.integer  "previous_tweet_ids",    limit: 8, array: true
end

add_index "tweets", ["previous_tweet_ids"], name: "index_tweets_on_previous_tweet_ids", using: :gin
add_index "tweets", ["project_id", "author_id"], name: "index_tweets_on_project_id_and_author_id", using: :btree
add_index "tweets", ["project_id", "twitter_id"], name: "index_tweets_on_project_id_and_twitter_id", unique: true, using: :btree
add_index "tweets", ["project_id"], name: "index_tweets_on_project_id", using: :btree

previous_tweet_ids是一个存储twitter_id所有先前推文的 Postgres 数组。我正在寻找一种方法来有效地检索一组推文的先前推文。这就是我目前正在做的事情:

# app/models/tweet.rb
class Tweet
  def previous_tweets
    @previous_tweets ||= project.tweets.where(twitter_id: previous_tweet_ids)
  end

  def future_tweets
    @future_tweets ||= project.tweets.where('previous_tweet_ids && ARRAY[?]', twitter_id)
  end
end

有没有办法将这些previous_tweetsfuture_tweets方法转换为 ActiveRecord 关联,以使用 ActiveRecord 的急切加载Tweet.incoming.includes(:previous_tweets, :future_tweets)

感谢您提前提供任何指示。

4

0 回答 0