【发布时间】:2016-07-27 18:16:58
【问题描述】:
我将 Rails 从 3.2 迁移到 Rails 4.2.6。我有 2 个表,其中 报告:has_many => 图标。我为报告和图标属性添加了强大的参数。创建功能工作正常,在更新功能时,我可以更新报告但无法更新图标,而是每次点击更新操作时都会创建新图标。 这是我的代码:
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
报告控制器:
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
我通过将 puts 放入控制器中看到了日志,图标在 @report.update_attributes(report_params) 步骤插入,这是日志:
由 ReportsController#update 处理为 JSON 参数: {"utf8"=>"✓", "report"=>{"title"=>"title1", "cmets"=>"这是一条评论", "icons_attributes"=>{"0"=>{"id"=>"", "icon"=>"market_indicator", "rotation"=>"0", "top"=>"", "_destroy"=>"false"}, "id"=>"87"}
报告负载 (0.3ms) SELECT "reports".* FROM "reports" WHERE "reports"."deleted_at" IS NULL AND "reports"."id" = ?限制 1 [["id", 87]]
SQL (1.6ms) INSERT INTO "icons" ("icon", "rotation", "top") 值 (?, ?, ?) [["icon", "market"], ["rotation", "0"], ["top", ""], ["left", ""]] (12.0ms) 提交事务
ActiveRecord::Associations::CollectionProxy
我把日志写成:
def update
puts @report.icons.inspect
respond_to do |format|
.....
end
结果如下:
图标加载 (0.9ms) SELECT "icons".* FROM "icons" WHERE "icons"."report_id" = ? ORDER BY position_id ASC [["report_id", 91]]
<ActiveRecord::Associations::CollectionProxy [#<Icon id: 204, report_id: 91, icon: "asking_price", rotation: "", top: "150", left: "165">]>
【问题讨论】:
-
您能否将传入的参数发布到您的更新操作中?
-
正如我在问题中发布的那样,我使用 report_params 作为更新操作的参数。
-
我的意思是从日志中发布参数。它们应该看起来像
Parameters: {"report"=> { "title" => "blah", "icons_attributes" => { etc. } }} -
icons_attributes我认为应该是一个数组。 -
我在日志中添加了请检查
标签: ruby-on-rails activerecord strong-parameters