【问题标题】:how to handle "synonymns" in a has_many relationship如何处理 has_many 关系中的“同义词”
【发布时间】:2014-02-01 23:30:33
【问题描述】:

这是一个棘手的问题。我有一个 Rails 关联,但需要添加功能来处理一些特殊情况。

class Item < ActiveRecord::Base
  has_many :notes
end

class Note < ActiveRecord::Base
  belongs_to :item
end

问题是您可能在 db 中有这样的东西(相同的项目可能在尺寸或数量上有所不同,但属于 desc 的一部分,并且由于会计软件而无法真正分解):

items 
id    desc
1     a glass something
..
10    a bottle of something
..
20    a case of bottles of something


notes
id   note                           item_id
3    "a note about something"       1

我想要做的是创建一个链接,以便项目 1,10 和 20 在加载笔记时都将加载 id 为 1 的笔记

例如:

item1=Item.find(1)
item1.notes[0].id  # 3

item10=Item.find(10)
item10.notes[0].id  # 3

item20=Item.find(20)
item20.notes[0].id  # 3

我觉得应该有一个非常基本的方法来做到这一点,并且正在寻找建议。这很 hacky,但可能的工作是将破折号分隔的 other_ids 列表写入 notes 表,以便 notes.other_ids="-10--20-"

class Item < ActiveRecord::Base
  has_many :notes

  def sym_items
    Note.where('other_ids like ?',"%-#{self.id}-%")
  end
end

我们真的只需要在一个场景中处理这个问题,所以一个hacky sol'n woudl 没问题,但显然希望更好。可能做一个 has_many :through。我不确定后者——也许增加了太多的复杂性。任何帮助或建议将不胜感激。

谢谢

【问题讨论】:

    标签: ruby-on-rails design-patterns activerecord ruby-on-rails-3.2 associations


    【解决方案1】:

    所以我不确定我是否完全理解这种情况。看起来你可能想要这样的东西:

    class Item < ActiveRecord::Base
      has_many :notes
      has_many :other_item_notes
      has_many :other_notes, class_name: "Note", through: :other_item_notes, source: :note
      has_many :other_items, class_name: "Item", through: :notes, source: :other_items
    end
    
    class Note < ActiveRecord::Base
      belongs_to :item
      has_many :other_item_notes
      has_many :other_items, class_name: "Item", through: :other_item_notes, source: :item
    end
    
    class OtherItemNote < ActiveRecord::Base
      belongs_to :item
      belongs_to :note
    end
    

    这里的诀窍是你在项目和笔记之间有一个多对多的关联(我假设你知道这些其他关联应该如何/为什么起作用)。然后我们使用我们现在可以访问的那些其他项目的关联来访问它们的关联项目。 N+1 查询等可能会出现复杂情况,但其中一些可以通过在您的关联中使用 inverse_of 来解决。

    如果您这样做,您将在数据库搜索中查询已索引的 id 列,而不是像上面示例中那样的字符串比较查询。

    【讨论】:

      猜你喜欢
      • 2018-06-14
      • 2023-03-16
      • 1970-01-01
      • 2018-07-16
      • 1970-01-01
      • 2017-06-18
      • 1970-01-01
      • 1970-01-01
      • 2013-05-05
      相关资源
      最近更新 更多