嵌套表单不保存在rails 3.1中

时间:2013-02-05 21:07:34

标签: ruby-on-rails models nested-forms nested-attributes

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”=&gt;“✓”,“authenticity_token”=&gt;“s7ksuk40M2r76Nq4PGEEpTpkCECxFniP4TtpfSHszQk =”,“symptom_set”=&gt; {“symptoms_attributes”=&gt; {“0”=&gt; {“名称“=&gt;”咳嗽“,”_ destroy“=&gt;”假“,”持续时间“=&gt;”2“},”1 “=&gt; {”name“=&gt;”Fever“,”_ destroy“=&gt;”false“,”duration“=&gt;”2“},”2“=&gt; {”name“=&gt;” “,”_ destroy“=&gt;”1“,”duration“=&gt;”“}}},”commit“=&gt;”创建症状集“}   用户负载(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)  返回“id”[[“created_at”,星期二,2013年2月5日21:12:07 UTC +00:00],[“updated_at”,星期二,05二月20 13 21:12:07 UTC +00:00],[“user_id”,1]]    (1.1ms)COMMIT

1 个答案:

答案 0 :(得分:0)

我试着改变:

@symptom_set = current_user.symptom_sets.build(params[:symptom_sets])

为:

@symptom_set = current_user.symptom_sets.new(params[:symptom_sets])

我不知道build是否可以在那里工作。

还检查终端日志上的参数是否被调用symptom_sets,以及它是否发送了嵌套表单属性的参数。

修改

我真的认为你的param的名字是symptom_set的单数。检查一下。