左外连接Rails中的嵌套选择

时间:2016-01-06 01:05:27

标签: ruby-on-rails associations

我试图建立一个经典的'喜欢'博客上的帖子模型,用户可以为任何帖子创建一个。我有以下型号:

class Post < ApplicationRecord
  belongs_to :user
  has_many :likes
end

class User < ApplicationRecord
  has_many :posts
  has_many :likes
end

class Like < ApplicationRecord
  belongs_to :user
  belongs_to :post, counter_cache: true
end

在我的控制器中,我监控当前登录的用户current_user

我想在帖子模型中添加一个列,指示current_user是否喜欢每个帖子。

我尝试在Posts模型中添加一个查找喜欢的方法:

class Post < ApplicationRecord
  belongs_to :user
  has_many :likes
  def user_liked
    !likes.empty?
  end
end

在控制器方法中使用includes

@posts = Post.includes(likes: { user: current_user }).where(safe_params).order(order)
render json: @posts

但是我收到以下错误:

ArgumentError (#<User id: 1, username: "pete", ... > was not recognized for preload):
app/controllers/posts_controller.rb:51:in `index'

我正在使用Rails API 5.0。

更新

为了澄清,我正在寻找与此SQL语句等效的Rails:

SELECT * 
FROM Posts
LEFT OUTER JOIN
    (SELECT * 
     FROM Likes
     WHERE Likes.user_id = current_user.id) AS MyLikes
ON Posts.id = MyLikes.post_id

1 个答案:

答案 0 :(得分:0)

问题是includes将关联名称作为参数(如:user, :likes, :posts)作为参数,并且不包含任何实例(在您的情况下为current_user

您可以尝试以下方式。

@posts = Post.includes(likes: :user).where(safe_params).order(order)

如果你想检查帖子是否属于current_user(例如haml视图)

- @posts.each do |post|
  - if post.likes && post.likes.any? { |like| like.user_id == current_user.id } 
    %span You have commented on this post