Noobの質問、確かですが、間違いを見つけることができないようです。SymptomSetsは適切なuser_idで保存されていますが、ネストされた症状は消えます。ユーザーモデルの構造は、Railsチュートリアルの構造と同じであることに注意してください(has_many:symptom_setsを保存してください)。
モデル:
class SymptomSet < ActiveRecord::Base
attr_accessible :symptoms, :symptoms_attributes
belongs_to :user
has_many :symptoms, :dependent => :destroy
accepts_nested_attributes_for :symptoms, allow_destroy: true
end
class Symptom < ActiveRecord::Base
attr_accessible :name, :duration, :symptom_set_id
belongs_to :symptom_set
end
コントローラ:
class SymptomSetsController < ApplicationController
before_filter :signed_in_user, only: [:create, :new]
def new
@symptom_set = SymptomSet.new
3.times do
symptom = @symptom_set.symptoms.build
end
end
def create
@symptom_set = current_user.symptom_sets.build(params[:symptom_sets])
if @symptom_set.save
flash[:success] = "Symptoms submitted!"
redirect_to root_url
else
render 'static_pages/home'
end
end
そしてビュー:
<%= simple_form_for @symptom_set, :html => { :class => 'form-inline' } do |f| %>
<%= f.fields_for :symptoms do |builder| %>
<%= render 'symptom_fields', f: builder %>
<% end %>
<div class="actions"><%= f.submit %></div>
<% end %>
そして部分的:
<%= f.input :name,
:collection=> ["Cough", "Fever", "Headache", "Lethargy"],
label: "Symptom",
prompt: "Select a symptom",
:input_html => { :class => "span3" }%>
<%= f.input :duration,
:collection => 1..14,
label: "Duration",
prompt: "How many days?" %>
最後に、railsサーバーコンソールは以下を出力します。
パラメータ:{"utf8" => "✓"、 "authenticity_token" => "s7ksuk40M2r76Nq4PGEEpTpkCECxFniP4TtpfSHszQk ="、 "symptom_set" => {"symptoms_attributes" => {"0" => {"name" => "Cough"、 " _destroy "=>" false "、" duration "=>" 2 "}、" 1 "=> {" name "=>" Fever "、" _destroy "=>" false "、" duration "=>" 2 " }、 "2" => {"name" => ""、 "_ destroy" => "1"、 "duration" => ""}}}、 "commit" => "Create Symptom set"} User Load( 0.4ms)SELECT"users"。*FROM "users"WHERE"users"。"remember_token"='OH6_nuvySNjd6AbTuDunsw' LIMIT 1
(0.1ms)BEGIN SQL(0.4ms)INSERT INTO "symptom_sets"( "created_at"、 "updated_at"、 "user_id")VALUES($ 1、$ 2、$ 3)RETURNING "id" [["created_at"、Tue、05 Feb 2013 21:12:07 UTC +00:00]、["updated_at"、火、05 Feb 20 13 21:12:07 UTC +00:00]、["user_id"、1]](1.1ms)COMMIT