2012-11-17 14 views
2

在rails中,我使用other_ids=[...]方法在has_many :through關聯上分配連接。它工作正常,除非我不想將other_ids=[...]提交給數據庫(使用此方法自動保存)。使用collection_singular_ids = ids而不保存到數據庫

有沒有辦法在使用Model.new時分配這些連接?舉例說明什麼時候有用,是因爲我提交的表單具有has_many關係的複選框。當表單不存儲時(當驗證失敗時),選中的複選框將被重置。

型號:

class Job < ActiveRecord::Base 
    has_many :categories 
    attr_accessible :category_ids 
end 

查看:

select :category_ids, Category.all.collect {|x| [x.name, x.id]}, {}, {:multiple => true} 

回答

1

這很奇怪。我的意思是,我明白它爲什麼會保存,因爲它是其他記錄的關係,而不是你正在使用的那個記錄,但我認爲應該很容易在AR中實現該功能。

無論如何,你可以做下面的事情來解決這個問題。使用虛擬屬性

class Bar < ActiveRecord::Base 
    after_save :save_foos 
    has_many :foos 

    attr_accessor :temp_foo_ids # Bad name for it but whatever... 
    attr_accessible :temp_foo_ids 

    def save_foos 
    foo_ids = temp_foo_ids # it should save the record like this again right? 
    end 
end 

在視圖中,也將使用虛擬屬性

select :temp_foo_ids, Foo.all.collect {|x| [x.name, x.id]}, {}, {:multiple => true} 

我沒有測試過這個事情,但我相信它會工作;)

相關問題