[英]How do I set a filter that will reject existing records when using accepts_nested_attributes_for
I have a Message and Source model related as follows: 我有一个与以下内容相关的消息和源模型:
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
When I submit my form (built using form_for
and fields_for
) it filters out any new sources with blank hrefs. 当我提交表单(使用
form_for
和fields_for
)时,它会过滤出所有带有空白href的新资源。 But what I want is for it to delete any existing sources whose hrefs have been set to blank. 但是我想要的是删除所有href设置为空白的现有来源。 Is there a simple way to do that?
有没有简单的方法可以做到这一点?
Hi Inside your Message
model you may add validates_associated :sources
If you need clear all Message
records with blank :href
from your database before saving new ones then inside your controller you may write 嗨,在您的
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.