我在用户和目标之间有一对一的关系。我想构建一个显示用户目标的表单。问题是,只有当用户已经定义了目标时,我的代码才能工作。当不存在目标时,不呈现文本字段。
<%= user_builder.fields_for :goal do |goal_builder| %>
<%= goal_builder.text_field :goal %>
<% end %>Rails提供了一种简单的方法来实现这一点吗?
发布于 2011-05-03 23:31:18
这就是我要做的:
class User < ActiveRecord::Base
has_one :goal
accepts_nested_attributes_for :goal
after_initialize do
self.goal ||= self.build_goal()
end
end发布于 2011-05-04 00:03:27
使用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上的文档。
https://stackoverflow.com/questions/5871796
复制相似问题