rails 4.2.0接受嵌套属性,但不起作用

时间:2015-01-20 21:17:42

标签: ruby-on-rails

我有一个简单的调查,其中有几个部分本身就是模型。我将这些部分一次一个地添加到调查表中,但第一个部分失败了。问题是,在呈现表单时,“demographics_part”字段不会显示在表单中。

我的模型都正确地连接在一起,正如在控制台中证明的那样:

Loading development environment (Rails 4.2.0)
2.2.0 :001 > s = Survey.last
  Survey Load (0.6ms)  SELECT  `surveys`.* FROM `surveys`  ORDER BY     `surveys`.`id` DESC LIMIT 1
 => #<Survey id: 1, confirmed_at: nil, created_at: "2015-01-20 20:06:38",     updated_at: "2015-01-20 20:06:38">
2.2.0 :002 > s.demographics_part
  DemographicsPart Load (0.6ms)  SELECT  `demographics_parts`.* FROM `demographics_parts` WHERE `demographics_parts`.`survey_id` = 1 LIMIT 1
 => #<DemographicsPart id: 3, name: "foo", created_at: "2015-01-20 20:06:38", updated_at: "2015-01-20 20:06:38", survey_id: 1>
2.2.0 :003 > d = DemographicsPart.find(3)
  DemographicsPart Load (0.9ms)  SELECT  `demographics_parts`.* FROM `demographics_parts` WHERE `demographics_parts`.`id` = 3 LIMIT 1
 => #<DemographicsPart id: 3, name: "foo", created_at: "2015-01-20 20:06:38", updated_at: "2015-01-20 20:06:38", survey_id: 1>
2.2.0 :004 > d.survey
  Survey Load (0.8ms)  SELECT  `surveys`.* FROM `surveys` WHERE `surveys`.`id` = 1 LIMIT 1
 => #<Survey id: 1, confirmed_at: nil, created_at: "2015-01-20 20:06:38", updated_at: "2015-01-20 20:06:38">
2.2.0 :005 > s = Survey.new
 => #<Survey id: nil, confirmed_at: nil, created_at: nil, updated_at: nil>
2.2.0 :006 > s.build_demographics_part
 => #<DemographicsPart id: nil, name: nil, created_at: nil, updated_at: nil, survey_id: nil>
2.2.0 :007 > d = s.build_demographics_part
 (0.2ms)  BEGIN
 (0.1ms)  COMMIT
   => #<DemographicsPart id: nil, name: nil, created_at: nil, updated_at: nil, survey_id: nil>
  2.2.0 :008 > d.name = "bar"
 => "bar"
  2.2.0 :009 > s.save
 (0.3ms)  BEGIN
    SQL (0.5ms)  INSERT INTO `surveys` (`created_at`, `updated_at`) VALUES ('2015-01-20 21:09:02.625560', '2015-01-20 21:09:02.625560')
    SQL (0.4ms)  INSERT INTO `demographics_parts` (`name`, `survey_id`, `created_at`, `updated_at`) VALUES ('bar', 2, '2015-01-20 21:09:02.630175', '2015-01-20 21:09:02.630175')
     (9.6ms)  COMMIT 
   => true  

这是我的表格:

<%= form_for(@survey) do |f| %>
    <div class="row collapse">
      <div class="small-3 columns">
        <%= f.label :confirmed_at, class: "right inline", title: "Last Confirmed", data: {tooltip: true} %>
      </div>
      <div class="small-9 columns"><%= @survey.confirmed_at %></div>
    </div>

      <% f.fields_for :demographics_part do |d| %>
        <%= d.label :name, "Name" %>
      <% end %>

    <div class="row collapse">
      <div class="small-9 small-offset-3 columns"><%= f.submit %></div>
    </div>
    <% end %>

这是我的控制器:

# GET /surveys/new
def new  
  @survey = Survey.new
  @d = @survey.create_demographics_part
end

我没有看到什么是错的。

1 个答案:

答案 0 :(得分:2)

更改 <% f.fields_for :demographics_part do |d| %>

使用: <%= f.fields_for :demographics_part do |d| %>

错误是因为您没有打印fields_for(=之后的%