【问题标题】:How to join tables not by table_id如何不按 table_id 连接表
【发布时间】:2023-04-05 10:24:01
【问题描述】:

我需要(被命令)通过 CODE 列(字符串)连接两个表。但是连接表Product.joins(:skus) 的默认(和正确)方法是通过ID=TABLE_ID 解决这种情况最好的方法是什么,有没有办法不用写:

Product.joins("INNER JOIN skus ON skus.CODE = products.CODE")

【问题讨论】:

    标签: ruby-on-rails activerecord rails-activerecord


    【解决方案1】:

    根据ActiveRecord 的文档,您可以指定关系的primary_key 和foreign_key。

    product.rb:

    class Product < ApplicationRecord
      has_many :skus, foreign_key: :code, primary_key: :code
    end
    

    sku.rb:

    class Sku < ApplicationRecord
      belongs_to :product, foreign_key: :code, primary_key: :code
    end
    

    现在您可以简单地使用Product.joins(:skus) 或Product.includes(:skus) 或事件Product.first.skus

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-01-09
      • 1970-01-01
      • 2018-08-15
      • 1970-01-01
      • 2018-03-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多