嵌套表单和一对一关系

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

   

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

我就是这样做的:

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

您可以使用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 

有关详细信息,请参阅有关嵌套属性的文档和form_for方法 。