gpt4 book ai didi

mysql - 包含 Rails 3 上的外部左连接

转载 作者:行者123 更新时间:2023-11-29 03:43:37 25 4
gpt4 key购买 nike

有没有办法执行 .includes 并指定一个外部左连接。

最初:

@post = Post.includes(:comments).where("comments.spam = ?", false).where(:id => params[:id]).first
@comments = post.comments

愿望是模仿:

@post = Post.find(params[:id])
@comments = post.comments.where(:spam => false)

除非使用 include 会以急切加载的方式执行它(如果说我有多个帖子)。

感谢您的帮助。贾斯汀

最佳答案

我会做以下事情:

class Post < ActiveRecord::Base
has_many :comments

has_many :non_spam_comments, :through => :comments, :conditions => {:spam => false}
has_many :spam_comments, :through => :comments, :conditions => {:spam => true}
end

然后,您将能够:

@posts = Post.where(:user_id => current_user.id).includes(:non_spam_comments)
@posts.each do |post|
post.non_spam_comments.each do |comment|
// Some comment operation
end
end

关于mysql - 包含 Rails 3 上的外部左连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9795815/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com