title: Ruby on Rails: Nested Attributes, belongs_to relation
body: <p>I have a User entity that has a Current Location field (city and country). To hold this info I created an entity called Location which has_many Users.</p>
  
  <p>I'm not entirely sure if I should put in the User model "has_one" or "belongs_to", but for what I read if I wanted it to have the foreign key of the location I should put "belongs_to". I also want to be able to edit the user's Current Location when editing the User. so I am using nested attributes. But when I edit the user I end up adding a new Location each time without ever associating it to the user that was edited. Can you help me out? </p>
  
  <p>My code is the following:</p>
  
  <pre><code>#User Model
  class User &lt; ActiveRecord::Base
    ## Relationships
    belongs_to :current_location, :class_name =&gt; 'Location'
    accepts_nested_attributes_for :current_location
  end
  
  #Location Model
  class Location &lt; ActiveRecord::Base
    #Relationship
    has_many :users
  end
  
  # part of the _form_edit.haml
  - form_edit.fields_for :current_location do |location_form|
    = location_form.label :location, "Current Location"
    = location_form.text_field :location
  
  #Application Helper
  #nested attributes for user and location
  def setup_user(user)
    returning(user) do |u|
      u.build_current_location if u.current_location.nil?
    end
  end
  
  #in the user controller (added after edit)
  def update
      @user = @current_user
      if @user.update_attributes(params[:user])
        flash[:notice] = "Account updated!"
        redirect_to account_url
      else
        render :action =&gt; :edit
      end
    end
  </code></pre>