21

問題:ネストされた属性を更新する代わりに、関連するアクションを実行すると、既存のネストされた属性の上に作成されます。#updatefeatures_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?チェックを達成するためのより良い方法があると確信しています。また、 Railscast #196 Nested Model Form (revised)の影響を強く受けて、いくつかの Javascript フックを使用して、動的にネストされたアトリビュート フォームを作成しています (省略しました)。

この種のネストされたフォームを処理するための、本当に素晴らしいRails-yの実装が欲しいです。

4

2 に答える 2