【问题标题】:Rails Error: joins + includeRails 错误:连接 + 包含
【发布时间】:2009-09-26 08:47:33
【问题描述】:

我有以下型号:

class Person < ActiveRecord::Base
 has_many :images
 has_one :preference
end

class Image < ActiveRecord::Base
 belongs_to :person
end

class Preference < ActiveRecord::Base
 belongs_to :person
end

我正在尝试获取所有公开的图像,同时渴望加载拥有这些图像的人:

    Image.find(:all, :conditions =>  ["images.person_id = ? AND preferences.image_privacy = ?", user.id, PRIVACY_PUBLIC],
               :joins => [:person => :user_preference], :include => :person)

Rails 似乎不喜欢 :include (我相信是因为 :person 在 2 个模型中被引用)。这是我得到的错误(当我删除 :include 选项时它消失了):

“ActiveRecord::StatementInvalid: Mysql::Error: Not unique table/alias: 'people'”

我可以通过将实际的 JOIN 命令写成字符串并将其传递给 :include 选项来解决这个问题,但这不是 Rails-y,所以我希望有一种更简洁的方法来做到这一点。

任何帮助将不胜感激。

谢谢!

【问题讨论】:

  • 能不能把sql查询贴到这里,日志里应该可以看到

标签: ruby-on-rails eager-loading


【解决方案1】:

看起来您将其称为“首选项”,而不是 user_preferences。所以你的加入应该是:

:joins => [:person => :preference])

【讨论】:

    【解决方案2】:

    通过使用 JOIN,您可以主动包含 People 表,因此您不需要再次添加“include”。这应该有效:

      Image.find(:all, :conditions =>  ["images.person_id = ? AND preferences.image_privacy = ?", user.id, PRIVACY_PUBLIC],
               :joins => [:person => :user_preference])
    

    【讨论】:

    • 这是不正确的,因为连接不会进行预加载。
    【解决方案3】:

    这可能是表格别名的问题,rails doc 在Table Aliasing 中有很多详细信息

    另外,在这里发布 SQL 也会很有用。

    【讨论】:

      【解决方案4】:

      你写了 :conditions => ["images.person_id", user.id] 并且你说你想加载图片和拥有这些图片的。但看起来您正在加载属于一个人(而不是一组人)的图像,因为您只指定了一个 user.id。

      我会这样做:

      Person.find(user.id, :include => [:images, :preference], :conditions => ["preferences.image_privacy = ?", PRIVACY_PUBLIC])
      

      它将加载人和他/她的图像。

      可能我没有正确理解您的问题,因为我认为您想要做的事情对我来说似乎不合逻辑。

      你可以试试named_scope而不是使用条件

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-06-01
        • 2012-04-14
        • 2021-12-22
        • 1970-01-01
        • 1970-01-01
        • 2017-12-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多