rails 4 double has_many包括

时间:2015-01-07 17:36:58

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

我遇到双重困难&包括

有一个Twitter风格的应用程序(包含用户,推文和喜欢)

class User
  has_many :tweets # direct tweets
  has_many :likes # liked tweets
end

class Tweet
  belongs_to :user 
  has_many :likes

class Like
  belongs_to :like
  belongs_to :user
end

这是点差查询:

@tweets = Tweet.first(20).includes(:likes) # I need to do includes or joins et.c.

我有一部分提交了一条推文,并向current_user说明了他对特定推文的状态(类似的情况):

(tweet.likes & current_user.likes).any? # I can't do efficient query here

我得到经典的n + 1查询。我应该怎么做才能阻止它?

2 个答案:

答案 0 :(得分:1)

试试这个:

class User
  has_many :tweets # direct tweets
  has_many :likes # liked tweets
end

class Tweet
  belongs_to :user 
  has_many :likes, through: :users

class Like
  belongs_to :like
  belongs_to :user
end

答案 1 :(得分:0)

在你的部分内容中,我认为你希望current_user喜欢那个推文。

在这种情况下,我会在视图中执行此操作:

current_user_likes_for_tweet = current_user.likes.select { |a| a.tweet_id == tweet.id }
(tweet.likes & current_user_likes_for_tweet).any?

这样,Rails会缓存current_user.likes,你只是对内存中的数组进行过滤。

也可以这样做:

<强>控制器

@current_user_likes = current_user.likes.group_by(&:tweet_id)

查看

(tweet.likes & @current_user_likes[tweet.id].to_a).any? # to_a because it might be nil