嵌套表格和一对一关系

时间:2011-05-03 15:22:29

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

我在用户和目标之间有一对一的关系。我想构建一个显示用户目标的表单。问题是我的代码仅在用户已定义目标时才有效。当没有目标时,不会呈现文本字段。

<%= user_builder.fields_for :goal do |goal_builder| %>
   <%= goal_builder.text_field :goal %>
<% end %>

Rails是否提供了一种简单的方法?

2 个答案:

答案 0 :(得分:6)

我就是这样做的:

class User < ActiveRecord::Base
  has_one :goal
  accepts_nested_attributes_for :goal
  after_initialize do
    self.goal ||= self.build_goal()
  end
end

答案 1 :(得分:1)

您可以使用accepts_nested_attributes_for轻松完成此操作。

在视图中,如您所见:

<%= user_builder.fields_for :goal do |goal_builder| %>
  <%= goal_builder.text_field :goal %>
<% end %>

在用户模型中:

class User < ActiveRecord::Base
  has_one :goal # or belongs_to, depending on how you set up your tables
  accepts_nested_attributes_for :goal
end

有关详情,请参阅nested attributes上的文档和form_for method