【问题标题】:ActiveRecord joining nested associations on non default valuesActiveRecord 在非默认值上加入嵌套关联
【发布时间】:2014-07-03 16:19:38
【问题描述】:

在你问之前,我无法控制在我正在使用的数据库中创建任何视图或连接表。

我在 ActiveRecord 文档中找到了可以进行多级连接的地方:

12.2.4 Joining Nested Associations (Multiple Level)

Category.joins(articles: [{ comments: :guest }, :tags])
This produces:

SELECT categories.* FROM categories
  INNER JOIN articles ON articles.category_id = categories.id
  INNER JOIN comments ON comments.article_id = articles.id
  INNER JOIN guests ON guests.comment_id = comments.id
  INNER JOIN tags ON tags.article_id = articles.id

你可以在哪里指定加入什么

Client.joins('LEFT OUTER JOIN addresses ON addresses.client_id = clients.id')

我想做的是结合2的东西

Client.joins('Inner Join addresses on addresses.client_name = client.name').joins('Inner Join state on state.abreviation = addresses.state_abreviation)

或在原始 sql 中

Select client.* from client 
Inner Join addresses on client.client_name = addresses.client_name
Inner Join state on addresses.state_abreviation = state.abreviation

如果我可以使用关联而不是连接来做到这一点,那就太好了!:

class Category < ActiveRecord::Base
  has_many :articles
end

class Article < ActiveRecord::Base
  belongs_to :category
  has_many :comments
  has_many :tags
end

class Comment < ActiveRecord::Base
  belongs_to :article
  has_one :guest
end

class Guest < ActiveRecord::Base
  belongs_to :comment
end

class Tag < ActiveRecord::Base
  belongs_to :article
end

【问题讨论】:

  • 看起来有addresses 表和您在此处省略的关联模型。对吗?
  • @San 我包含了我正在寻找的内容“我想做的是结合 2 的东西”
  • 您描述了具有关联的活动记录模型,这与您在第二个连接请求中编写的表和模型不同。这令人困惑,并且与 Active Record 模式不匹配

标签: ruby-on-rails ruby activerecord


【解决方案1】:

使用 Arel:

c = Client.arel_table
a = Adress.arel_table
s = State.arel_table
query = Client.all.arel
         .join(a)
           .on(a[:client_name].eq(c[:client_name]))
         .join(s)
           .on(s[:abreviation].eq(a[:state_abreviation]))
Client.find_by_sql(query.to_sql)

【讨论】:

    【解决方案2】:

    您可以使用“通过” 对于您的类别模型,这些将是这样的

    class Category < ActiveRecord::Base
      has_many :articles
      has_many :comments, through: :articles
      has_many :tags, through: :articles
    end
    
    Category.last.tags
    => tags
    Category.last.articles
    => articles
    

    【讨论】:

    • 这根本不能解决我的问题。我正在寻找如何进行自定义列关联
    • 我为您描述的 db 模式写了答案
    【解决方案3】:

    我找到了答案。您需要为表定义 foreign_key 以便将其映射回来。

      belongs_to :addresses, foreign_key: 'state_abreviation'
    

    【讨论】:

    • 用户无法理解您的回答,因为您没有描述您的数据库结构
    • 干得好,您查看了 rails 手册 :) ....aa 而这只是您的问题的开始 :) 尝试使用查询和更复杂的范围
    • 对此进行扩展,请查看stackoverflow.com/questions/24685837/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-06
    • 2011-10-07
    • 1970-01-01
    • 1970-01-01
    • 2014-11-14
    • 1970-01-01
    相关资源
    最近更新 更多