1

好的,这个是一个doozy。我有一个 ActiveRecord 对象,其中包括如下关系:

class Sample < ActiveRecord::Base
  has_and_belongs_to_many :related_samples,
                          :class_name => "Sample",
                          :join_table => "related_samples",
                          :foreign_key => "sample_id"
                          :associated_foreign_key => "related_id"
end

这是它的方案:

def self.up
  create_table :samples do |t|
    t.string :related_info
    t.string :name
    #There's other info, but it is not related to this problem
  end

  create_table :related_samples, :id => false do |t|
    t.references :sample
    t.references :related
    t.timestamps
  end
end

这完美地工作。当我要求 sample_object.related_samples 时,它会给我分配给它的任何其他 Sample 对象。

问题来自我的视图的编辑操作。我的目标是允许用户通过从所有可用样本的列表中选择现有的相关样本对象来将其替换为不同的样本。我想在 fields_for 辅助方法中实现这个(如果可能的话),所以更新非常简单。我不确定如何实现这一点,或者我什至可以。可能吗?如果是这样,怎么办?

4

1 回答 1

0

我刚刚意识到一些非常重要的事情,可能会使这个问题无法解决。当我说我希望能够更改另一个与之相关的 Sample 对象时,我的意思是对它的引用。例子:

Sample1.related_sites == [Sample2, Sample3]

我想做一些事情,以便我可以使用 Sample4 代替另一个 Sample,这样它就变成了:

Sample1.related_sites == [Sample2, Sample4]

但我希望 Sample3 保持完整。这意味着需要更改引用,我认为没有任何比修改我的数据库方案更容易的方法。所以,如果你还有一个想法,我很想听听,但我可能会改变一些事情。谢谢,社区!

于 2010-02-23T19:24:56.550 回答