nested forms and one to one relationship

两盒软妹~` 提交于 2019-12-24 02:31:27

问题


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 %>

Does Rails provide an easy way to do this?


回答1:


This is how I would do it :

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



回答2:


You can do this very easily with accepts_nested_attributes_for.

In the view, as you had:

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

In the User model:

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

See the documentation on nested attributes, and the form_for method for more information.



来源:https://stackoverflow.com/questions/5871796/nested-forms-and-one-to-one-relationship

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!