嵌套形式和一对一关系 [英] nested forms and one to one relationship
本文介绍了嵌套形式和一对一关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我与用户和目标之间是一对一的关系.我想构建一个显示用户目标的表单.问题是我的代码仅在用户已经定义了目标时才有效.如果没有目标,则不会显示文本字段.
I have a one-to-one relationship between user and goal. I want to build a form that shows the goal of a user. The problem is that my code only works when the user already has a goal defined. The text field is not rendered when no goal is present.
<%= user_builder.fields_for :goal do |goal_builder| %>
<%= goal_builder.text_field :goal %>
<% end %>
Rails提供了一种简便的方法吗?
Does Rails provide an easy way to do this?
推荐答案
这就是我的做法:
class User < ActiveRecord::Base
has_one :goal
accepts_nested_attributes_for :goal
after_initialize do
self.goal ||= self.build_goal()
end
end
这篇关于嵌套形式和一对一关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文