Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/design-patterns/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 如何处理;同义词;在一段感情中_Ruby On Rails_Design Patterns_Activerecord_Ruby On Rails 3.2_Associations - Fatal编程技术网

Ruby on rails 如何处理;同义词;在一段感情中

Ruby on rails 如何处理;同义词;在一段感情中,ruby-on-rails,design-patterns,activerecord,ruby-on-rails-3.2,associations,Ruby On Rails,Design Patterns,Activerecord,Ruby On Rails 3.2,Associations,这是一个有点棘手的问题。我有一个Rails关联,但需要添加功能来处理一些特殊情况 class Item < ActiveRecord::Base has_many :notes end class Note < ActiveRecord::Base belongs_to :item end 我要做的是创建一个链接,这样当项目1、10和20加载注释时,它们都将加载id为1的注释 例如: item1=Item.find(1) item1.notes[0].id # 3 i

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

class Item < ActiveRecord::Base
  has_many :notes
end

class Note < ActiveRecord::Base
  belongs_to :item
end
我要做的是创建一个链接,这样当项目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
我觉得应该有一个真正基本的方法来做这件事,我正在寻找建议。这是一个很有技巧的方法,但可能需要将其他_id的破折号分隔列表写入notes表,以便a
notes.other_id=“-10--20-”

class项
我们真的只需要在一个场景中处理这个问题,所以黑客sol'n是可以的,但显然会更好。可能做了很多:通过。我不确定后者——可能太复杂了。任何帮助或建议都将不胜感激


thx

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

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
class项
这里的诀窍是,条目和注释之间存在多对多关联(我假设您知道这些其他关联应该如何/为什么工作)。然后,我们使用现在可以访问的那些其他项的关联来访问它们的关联项。N+1查询等可能会有一些复杂的情况,但其中一些问题可以通过在关联上使用
inverse\u来解决

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

class Item < ActiveRecord::Base
  has_many :notes

  def sym_items
    Note.where('other_ids like ?',"%-#{self.id}-%")
  end
end
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