【问题标题】:In Rails 5 belongs_to, how do I disregard id and create accociation by unique name?在 Rails 5 belongs_to 中,如何忽略 id 并通过唯一名称创建 accociation?
【发布时间】:2019-07-19 14:24:52
【问题描述】:

我有一个具有这种关联的模型:

belongs_to :nesti_commodity,
  -> { where name: nesti_commodity },
  inverse_of: :commodity_to_products

CommodityToProducts 有 nesti_commodity 列,其中包含一个字符串。 我们没有nesti_commodity_id。

NestiCommodity 有 id 列和 name 列。我的高级同事希望它通过名称列关联,这是一个字符串,他想忽略 id。

如何在 Rails 5 中做到这一点?在这种情况下打破惯例的最干净的方法是什么?

【问题讨论】:

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


    【解决方案1】:

    我一直在寻找答案,因为我需要 has_many,通过:关联。

    最后我实现了自己的方法,叫做nesti_commodity_record,当我需要使用非标准关联时,我会使用这个约定。

    def nesti_commodity_record
      NestiCommodity.where(name: nesti_commodity).last
    end
    

    关于 has_many,通过:,我已经实现了自己的方法,使用 Arel 和连接。

    # this simulates has_many_through
    def nesti_commodity_records
      NestiCommodity.select(
        NestiCommodity.arel_table[Arel.star]
      ).where(
        CommodityToProduct.arel_table[:mrl_product_id].eq(id)
      ).joins(
        NestiCommodity.arel_table.join(CommodityToProduct.arel_table).on(
          NestiCommodity.arel_table[:name]
            .eq(CommodityToProduct.arel_table[:nesti_commodity])
        ).join_sources
      )
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-10-23
      • 1970-01-01
      • 1970-01-01
      • 2023-01-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多