需要nested_form示例

时间:2011-10-05 15:14:53

标签: ruby-on-rails-3 nested-forms

我放弃了。我正在尝试使用Railscasts#196剧集之后的2个模型构建一个简单的嵌套表单并且不起作用。有人可以发送一个工作示例,以便我可以测试我的环境。我正在使用3.1.0

例如,当我尝试在表单上构建3个问题时,只显示1个问题字段,则Survey_id永远不会传递。

我很感激你在2天两夜后的帮助。我错过了一些非常大的东西。感谢

模型

class Survey < ActiveRecord::Base
  has_many :questions, :dependent => :destroy
  accepts_nested_attributes_for :questions
  attr_accessible :name, :questions_attributes
end

class Question < ActiveRecord::Base
  belongs_to :survey
  attr_accessible :survey_id, :name
end

控制器

def new
@survey = Survey.new
4.times { @survey.questions.build }

respond_to do |format|
  format.html # new.html.erb
  format.json { render json: @survey }
end
end

def create
@survey = Survey.new(params[:survey])

respond_to do |format|
  if @survey.save
    format.html { redirect_to @survey, notice: 'Survey was successfully created.' }
    format.json { render json: @survey, status: :created, location: @survey }
  else
    format.html { render action: "new" }
    format.json { render json: @survey.errors, status: :unprocessable_entity }
  end
end
end

查看

<%= form_for(@survey) do |f| %>
  <% if @survey.errors.any? %>
  <div id="error_explanation">
   <h2><%= pluralize(@survey.errors.count, "error") %> prohibited this survey from being saved:</h2>
   <ul>
     <% @survey.errors.full_messages.each do |msg| %>
      <li><%= msg %></li>
     <% end %>
   </ul>
  </div>
<% end %>

<div class="field">
  <%= f.label :name %><br />
  <%= f.text_field :name %>
</div>

<%= fields_for :questions do |builder| %>
  <%= builder.label :name, "Question"  %>
  <%= builder.text_field :name %>
<% end %>

<br /><br />
<div class="actions">
 <%= f.submit %>
</div>
<% end %>

0 个答案:

没有答案