[英]How do I set an attribute on the join model when using accepts_nested_attributes_for?
[英]How do I set a filter that will reject existing records when using accepts_nested_attributes_for
我有一个与以下内容相关的消息和源模型:
class Message < ActiveRecord::Base
has_many :sources
accepts_nested_attributes_for :sources, :allow_destroy => true, :reject_if => proc{|s| s[:href].blank?}
end
class Source < ActiveRecord::Base
belongs_to :outgoing_message
validates_presence_of :href
end
当我提交表单(使用form_for
和fields_for
)时,它会过滤出所有带有空白href的新资源。 但是我想要的是删除所有href设置为空白的现有来源。 有没有简单的方法可以做到这一点?
嗨,在您的Message
模型内部,您可以添加validates_associated :sources
如果在保存:href
之前需要从数据库中清除所有带有空白:href
Message
记录,则可以在控制器内部编写
before_filter :some_filter, :only=>[:form_action]
...
def some_filter
Source.delete_all("href = '' OR href IS NULL")
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.