1

好吧,這個是一個很酷的。我有一個ActiveRecord對象,除其他事項外,包括關係如下:Rails自編的HABTM Active Record Object嵌套編輯表格

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 helper方法中實現這個(如果可能的話),這樣做更新非常簡單。我不知道如何實現這一點,或者我甚至可以。可能嗎?如果是這樣,怎麼樣?

+0

你有沒有解決過這個問題? – CharlieMezak 2011-11-11 23:10:08

回答

0

我剛剛意識到一件非常重要的事情,可能會使這個問題無法解決。當我說我希望能夠更改另一個與之相關的Sample對象時,我的意思是提及它。例如:

Sample1.related_sites == [Sample2, Sample3] 

我想要做的事,這樣我可以代替另一個樣品的使用Sample4,使之成爲:

Sample1.related_sites == [Sample2, Sample4] 

但我要樣品3保持不動。這意味着引用需要改變,我認爲沒有辦法以比修改我的數據庫方案更容易的方式進行。所以,如果你仍然有一個想法,我很樂意聽到它,但我很可能會改變一些事情。謝謝,SO社區!