I would appreciate your help on this:
I have 2 models:
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
In my form, i have got the following 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%>
Controller code:
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
Currently, if a user removes all the contents in the form field ‘note_value’ and update the form, the data row is still present in the ‘authornote’ table, with the column ‘note_value’ empty.
What i would like is that, if field ‘note_value’ is empty and user clicks on the update button, i would like the row with the empty column ‘note_value’ to be deleted in the ‘authornote’ table.
Any suggestion is most appreciated
What you’re trying to do is not supported by Rails as you’re trying to do it. In order for a record to be deleted through
accepts_nested_attributes_foryou have to pass_delete: truealong with the ID of the record to be deleted. When you reject the nested records that don’t have anote_valuethere’s no way for Rails to know you’re trying to update those records—they’re just missing from the params entirely.