I migrated my Rails from 3.2 to Rails 4.2.6. I am having 2 tables where report :has_many => icons. I added strong parameters for report and icon_attributes. The create functionality is working fine and when coming to update functionality, I am able to update reports but couldn't update icons, instead new icon is created every time it hits update action. This is my code:
report.rb:
class Report < ActiveRecord::Base
has_many :icons, -> { order 'position_id ASC'}
accepts_nested_attributes_for :icons, :reject_if => lambda { |a| a[:icon].blank? }, :allow_destroy => true
end
icon.rb:
class Icon < ActiveRecord::Base
belongs_to :report
end
reports_controller:
def update
respond_to do |format|
if @report.update_attributes(report_params)
@report.save
format.html { redirect_to(user_reports_url, :notice => 'Report was successfully updated.') }
format.json { render :json => { :success => true, :report_id => @report.id, :report_title => @report.title, :icon_array => @report.icons, :redirect => report_url(@report.id) } }
format.xml { head :ok }
else
format.html { render :action => "edit" }
format.xml { render :xml => @report.errors, :status => :unprocessable_entity }
end
end
end
private
def report_params
params.require(:report).permit(:title, :comments, :remarks,{:icons_attributes => [:id, :icon, :rotation, :top, :_destroy]})
end
I have seen the log by putting puts in the controller, the icons are inserting at @report.update_attributes(report_params) step and this is the log:
Processing by ReportsController#update as JSON Parameters: {"utf8"=>"✓", "report"=>{"title"=>"title1", "comments"=>"This is a comment", "icons_attributes"=>{"0"=>{"id"=>"", "icon"=>"market_indicator", "rotation"=>"0", "top"=>"", "_destroy"=>"false"}, "id"=>"87"}
Report Load (0.3ms) SELECT "reports".* FROM "reports" WHERE "reports"."deleted_at" IS NULL AND "reports"."id" = ? LIMIT 1 [["id", 87]]
SQL (1.6ms) INSERT INTO "icons" ("icon", "rotation", "top") VALUES (?, ?, ?) [["icon", "market"], ["rotation", "0"], ["top", ""], ["left", ""]] (12.0ms) commit transaction
ActiveRecord::Associations::CollectionProxy
I have put log as:
def update
puts @report.icons.inspect
respond_to do |format|
.....
end
it resulted as:
Icon Load (0.9ms) SELECT "icons".* FROM "icons" WHERE "icons"."report_id" = ? ORDER BY position_id ASC [["report_id", 91]]
Parameters: {"report"=> { "title" => "blah", "icons_attributes" => { etc. } }}- vichicons_attributesshould be an array I think. - Azolo