reject_if空?不工作 - 当字段为空
问题描述:
我将不胜感激您对此的帮助不会删除表行:reject_if空?不工作 - 当字段为空
我有2种型号:
class Author < ActiveRecord::Base
has_one :authornote, :foreign_key => "author_fk", :dependent => :destroy
accepts_nested_attributes_for :authornote, :reject_if => lambda { |a| a[:note_value].blank? }, :allow_destroy => true
end
class Authornote < ActiveRecord::Base
belongs_to :author, :foreign_key => :author_fk
end
在我的形式,我有以下field_for:
<% remote_form_for @author, :url => { :controller => "authors", :action => "update_author_note" } do |f| %>
<div>
<% f.fields_for :authornote do |builder| %>
<%= builder.text_area :note_value, :rows => 4, :cols => 50 %>
<% end %>
</div>
<%= f.submit 'Update' %>
<%end%>
控制器代码:
def update_author_note
author_id = session[:author_id]
@author = Author.find(author_id)
if @author.update_attributes(params[:author])
respond_to do |format|
format.js
end
else
respond_to do |format|
format.html { redirect_to add_author_note_path(:sub_id=> session[:sub_id]) }
end
end
end
当前,如果用户删除表单域'note_value'中的所有内容并更新表单,那么数据行仍存在于'authornote'表中,其中'note_value'列为空。
我想要的是,如果字段'note_value'是空的,并且用户单击更新按钮,我希望在'authornote'表中删除具有空列'note_value'的行。
任何建议最欣赏
答
什么你试图做你正在试图做的是不支持的Rails。为了通过accepts_nested_attributes_for
删除记录,您必须将_delete: true
连同要删除的记录的ID一起传递。当您拒绝没有note_value
的嵌套记录时,Rails无法知道您正在尝试更新这些记录—,他们完全从参数中缺失。
非常感谢澄清。干杯 – tanya 2012-01-10 11:20:26