gpt4 book ai didi

ruby-on-rails - 如何在 Rails 4 中合并(链接)2 个不同表上的关系

转载 作者:数据小太阳 更新时间:2023-10-29 07:19:52 24 4
gpt4 key购买 nike

给定 2 个生成以下 SQL 的 ActiveRecord 关系:

  • 关系 a = SELECT comments.* FROM comments INNER JOIN attachments ON attachments.comment_id = comments.id WHERE attachment.name ILIKE '%foo%
  • 关系 b = SELECT attachments.* FROM attachments INNER JOIN users ON attachments.user_id = users.id WHERE users.other_conditions

这在 Rails/ActiveRecord 3 中有效:

puts a.merge(b).to_sql # Rails 3
> "SELECT comments.* FROM comments INNER JOIN attachments ON attachments.comment_id = comments.id INNER JOIN users ON attachments.user_id = users.id WHERE attachment.name ILIKE '%foo% AND users.other_conditions"

我认为它有效,因为merge 忽略了查询中任何不存在的关联。

但是 Rails 4 更加迂腐,并且失败了:

puts a.merge(b).to_sql # Rails 4
> ActiveRecord::ConfigurationError: Association named 'user' was not found on Comment; perhaps you misspelled it?

所以问题是我如何真正合并这两个关系而不用担心 Rails 的正确性(我的规范对此负责)?

最佳答案

您能再描述一下您的模型及其关系吗?

对我来说,它是这样工作的:

class User
has_many :facebook_friends
end

class FacebookFriend
belongs_to :user
end

a = User.where("users.first_name LIKE '%Sandy%'")
b = FacebookFriend.where("facebook_friends.last_name LIKE '%John%'")
a.merge(b)

=> 用户负载 (0.5ms) SELECT users.* FROM users WHERE (users.first_name LIKE '%Sandy%') AND (facebook_friends.last_name LIKE ' %约翰%')

=> Mysql2::错误:“where 子句”中的未知列“facebook_friends.last_name”:SELECT users.* FROM users WHERE (users.first_name LIKE ' %Sandy%') AND (facebook_friends.last_name LIKE '%John%')

a.joins(:facebook_friends).merge(b)

=> 用户负载 (0.6ms) SELECT users.* FROM users INNER JOIN facebook_friends ON facebook_friends .user_uid = users.uid WHERE (users.first_name LIKE '%Sandy%') AND (facebook_friends.last_name LIKE '%John%' )

=> []

关于ruby-on-rails - 如何在 Rails 4 中合并(链接)2 个不同表上的关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17310106/

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