2013-03-12 42 views
0

我有一個模型訂閱與所屬關聯到參與者。不自動保存所屬關聯

訂閱表單使用fields_for來構建關聯的參與者字段。

此外,表單中還有一個叫做'other_person'的單選按鈕。

我想要的是在other_person字段設置爲false時不保存關聯的參與者表(因此也不會驗證)。

+0

請發表一些你已經嘗試過的代碼示例。 – fmendez 2013-03-12 22:12:32

回答

1

我會假設other_person是在下面的例子中Subscription模型的領域:

class Subscription < ActiveRecord::Base 
    before_save :remove_empty_participant 
    belongs_to :participant 

    private 

    def remove_empty_participant 
    self.participant = nil unless self.other_person 
    end 
end 

如果這不是你Subscription模型的領域,你將不得不在控制器的動作刪除屬性:

class SubscriptionsController < ActionController 

    def create 
    params[:subscription].delete(:participant) unless params[:other_person] 
    # Save the subscription with your current params... 
    end 

end 

希望它有幫助。

+0

謝謝other_person確實是Subscription模型的一個領域。我也嘗試過這個解決方案。它部分起作用,因爲它不保存訂閱模型中的關聯的participant_id。但是,它會將參與者保存在參與者表中。 (可能是因爲它先插入參與者,然後插入訂閱) – 2013-03-12 22:17:42

+0

是的,很可能。爲了獲得參與者id,參與者必須先保存。您是否嘗試了在進入'訂閱'模型之前清理'params'的替代方法? – sergelerator 2013-03-12 22:44:52

+0

是的,那可行! (雖然我使用:participant_attributes):)謝謝 – 2013-03-12 22:50:16