尽管常规属性可以正常工作,但我无法使用Rails更新嵌套属性。这是我的结构:
unit.rb:
class Unit < ApplicationRecord
has_many :unit_skill_lists
has_many :skill_lists, through: :unit_skill_lists, inverse_of: :units, autosave: true
accepts_nested_attributes_for :skill_lists, reject_if: :all_blank, allow_destroy: true
end
unit_skill_list.rb:
class UnitSkillList < ApplicationRecord
belongs_to :unit
belongs_to :skill_list
end
skill_list.rb:
class SkillList < ApplicationRecord
has_many :unit_skill_lists
has_many :units, through: :unit_skill_lists, inverse_of: :skill_lists
end
这是控制器(的一部分):
class UnitsController < ApplicationController
def update
@unit = Unit.find(params[:id])
if @unit.update(unit_params)
redirect_to edit_unit_path(@unit), notice: "Unit updated"
else
redirect_to edit_unit_path(@unit), alert: "Unit update failed"
end
end
private
def unit_params
unit_params = params.require(:unit).permit(
...
skill_list_attributes: [:id, :name, :_destroy]
)
unit_params
end
end
表格中的相关行(使用formastic和茧):
<%= label_tag :skill_lists %>
<%= f.input :skill_lists, :as => :check_boxes, collection: SkillList.where(skill_list_type: :base), class: "inline" %>
知道我要去哪里了吗?我尝试遵循所有可能找到的指南,但是更新对嵌套属性没有任何作用。
在Vasilisa的帮助下进行编辑:
当我尝试更新单元时,这是错误:
ActiveRecord::RecordInvalid (Validation failed: Database must exist):
这是完整的unit_skill_list.rb:
class UnitSkillList < ApplicationRecord
belongs_to :unit
belongs_to :skill_list
belongs_to :database
end
“数据库”没有输入字段。应该在更新单元时通过会话变量进行设置。
答案 0 :(得分:2)
如果查看服务器日志,则会在params hash中看到类似skill_list_ids: []
的内容。您不需要accepts_nested_attributes_for :skill_lists
,因为您不需要在单位创建/更新时创建新的SkillList。将允许的参数更改为:
def unit_params
params.require(:unit).permit(
...
skill_list_ids: []
)
end
更新
我认为最好的选择是设置optional
参数-belongs_to :database, optional: true
。并在控制器中手动更新。
def update
@unit = Unit.find(params[:id])
if @unit.update(unit_params)
@unit.skill_lists.update_all(database: session[:database])
redirect_to edit_unit_path(@unit), notice: "Unit updated"
else
redirect_to edit_unit_path(@unit), alert: "Unit update failed"
end
end