【发布时间】: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