问题:当我点击关联的操作时,它们不是更新嵌套属性,而是在现有嵌套属性之上创建#update
features_controller.rb
可能原因:我认为问题在于我对 Rails 的form_for
. 我认为故障在于我的观点,我如何呈现持久的嵌套属性,和/或我如何未能指定嵌套属性的 id,导致它只是创建一个新的
特征.rb
class Feature < ActiveRecord::Base
...
has_many :scenarios
accepts_nested_attributes_for :scenarios,
allow_destroy: true,
reject_if: :all_blank
...
end
features_controller.rb
def update
...
project = Project.find(params[:project_id])
@feature = Feature.find(params[:id])
if @feature.update_attributes(feature_params)
# checking feature_params looks good...
# feature_params['scenarios'] => { <correct object hash> }
redirect_to project
else
render :edit
end
end
...
private
def feature_params
params.require(:feature).permit(:title, :narrative, :price, :eta, scenarios_attributes[:description, :_destroy])
end
_form.html.haml(简体)
= form_for [@project, @feature] do |f|
...
- if @feature.new_record? -# if we are creating new feature
= f.fields_for :scenarios, @feature.scenarios.build do |builder|
= builder.label :description, "Scenario"
= builder.text_area :description, rows: "3", autocomplete: "off"
- else -# if we are editing an existing feature
= f.fields_for :scenarios do |builder|
= builder.label :description, "Scenario"
= builder.text_area :description, rows: "3", autocomplete: "off"
我确信有更好的方法来实现if @feature.new_record?
检查。我还使用一些 Javascript 钩子来创建动态嵌套属性表单(我已经忽略了),深受Railscast #196 嵌套模型表单(修订)的影响
我希望有一个非常好的Rails-y实现来处理这些嵌套表单。