Tarscher
Tarscher

Reputation: 1933

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

Does Rails provide an easy way to do this?

Upvotes: 2

Views: 1542

Answers (2)

Cl&#233;ment
Cl&#233;ment

Reputation: 1409

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

Upvotes: 6

Austin Taylor
Austin Taylor

Reputation: 5477

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.

Upvotes: 1

Related Questions