菜鸟问题,我敢肯定,但我似乎找不到我的错误。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"=>"创建症状集"} 用户负载 ( 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", 2 月 5 日星期二2013 年 21:12:07 UTC +00:00],["updated_at",星期二,2013 年 2 月 5 日星期二 21:12:07 UTC +00:00],["user_id",1]] (1.1ms) 提交