2013-03-12 38 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