简体   繁体   English

在使用accepts_nested_attributes_for时,如何设置将拒绝现有记录的过滤器

[英]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_forfields_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.

相关问题 使用accepts_nested_attributes_for时如何在联接模型上设置属性? - How do I set an attribute on the join model when using accepts_nested_attributes_for? Rails如何在accepts_nested_attributes_for时拒绝_if - Rails how to reject_if when accepts_nested_attributes_for Rails 3,多对多形式使用accepts_nested_attributes_for,如何正确设置? - Rails 3, many-to-many form using accepts_nested_attributes_for, how do I set up correctly? 创建新记录时如何使用accepts_nested_attributes_for? - How do you use accepts_nested_attributes_for when creating new records? accepts_nested_attributes_for - 如何拒绝空巢? - accepts_nested_attributes_for - How to reject empty nests? 使用Rails的accepts_nested_attributes_for功能时如何维护子记录的顺序? - How to maintain an order on child records when using Rails' accepts_nested_attributes_for feature? 如何使用accepts_nested_attributes_for? - How do I use accepts_nested_attributes_for? 在Rails中,如何使用accepts_nested_attributes_for创建嵌套对象? - In Rails, how do I create nested objects using accepts_nested_attributes_for? 使用 accepts_nested_attributes_for 创建新记录或更新现有记录 - Use accepts_nested_attributes_for to create new records or update existing 通过用于另一个对象的accepts_nested_attributes_for完成后,如何修改关联对象的创建? - How do I modify the creation of an associated object when done via accepts_nested_attributes_for for another object?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM