Rails 4.0嵌套对象表单未呈现

时间:2015-10-07 17:00:55

标签: ruby-on-rails ruby-on-rails-4

我的应用中有两个型号:“WorkPost”和“Contacts”。

WorkPost

 class WorkPost < ActiveRecord::Base
   has_one :contacts
 end

联系人

 class Contacts < ActiveRecord::Base
   belongs_to :work_post
 end

在我的控制器的new方法中,我做了:

def new
  @work_post = WorkPost.new
  @work_post.contacts
end

在视图中我创建了表单:

<%= form_for(@work_post) do |f| %>
<div class="field">
<%= f.label 'Vacation' %><br>
<%= f.text_field :post_title, :placeholder => 'Vacation here' %>
</div>
<div class="field">
  <%= f.label 'Vacation description' %><br>
 <%= f.text_area :post_body, :placeholder => 'Vacation description here' %>
</div>
  <% f.fields_for :contacts do |cf| %>
  <div class="field">
    <%= cf.label 'Email' %><br>
    <%= cf.text_field :emails, :placeholder => 'Email here' %>
  </div>
  <% end %>
<div class="actions">
<%= f.submit "Post vacation", :class => 'btn_act' %>
</div>
<% end %>

但似乎行<% f.fields_for :contacts do |cf| %>不起作用。 一切都很好,但电子邮件领域。我做错了什么?

1 个答案:

答案 0 :(得分:1)

问题在于这一行

<% f.fields_for :contacts do |cf| %>

应该是

<%= f.fields_for :contact do |cf| %>

此外,class name的{​​{1}}和model的{​​{1}}应为 单数 。< / p>

association name

此外,请注意更改has_one/belongs_to#work_post.rb class WorkPost < ActiveRecord::Base has_one :contact #should be singular end #contact.rb class Contact < ActiveRecord::Base #should be singular belongs_to :work_post end ,因为它是:contacts关联。

<强> 更新

另外,请尝试以下更改

:contact模型中加入has_one

accepts_nested_attributes_for :contact

work_post.rb方法更改为

#work_post.rb
class WorkPost < ActiveRecord::Base
  has_one :contact
  accepts_nested_attributes_for :contact
end