And*_*w K 1 ruby ruby-on-rails ruby-on-rails-4
我正在使用 Devise gem 在 Heroku 上运行 Rails 4。
我有两个模型有问题:帖子和投票。我正在尝试查找用户尚未投票的所有帖子。我无法找出使用 rails ActiveRecord 进行此查询的正确方法。到目前为止,我已经尝试过:
@posts = Post.includes(:votes).where('votes.user_id != ?', current_user.id)
Run Code Online (Sandbox Code Playgroud)
我试过:
@posts = Post.joins(:votes).where.not( votes: {user_id: current_user.id})
Run Code Online (Sandbox Code Playgroud)
没有得到任何结果。
在模型中,我将 Has_many 关系设置为:
class Post < ActiveRecord::Base
belongs_to :user
has_many :images, dependent: :destroy
has_many :votes, dependent: :destroy
end
Run Code Online (Sandbox Code Playgroud)
对于更有经验的人来说,这可能是一个容易回答的问题,但我尝试通过RailsGuides Active Record Query Interface进行搜索,但无济于事。
用
@posts = Post.includes(:votes).where('votes.user_id <> ? or votes.user_id is null', current_user.id)
Run Code Online (Sandbox Code Playgroud)
我想您的查询没有检索 3 条记录,votes.user_id因为它们为空。