Search code examples
ruby-on-railsdeviseform-forbelongs-tohas-one

Using form_for for one-to-one relation model in rails


I have a one-to-one models for user and profile.

The following is the code for the User model created by device.

class User < ActiveRecord::Base  
  has_one :profile , dependent: :destroy
end

Code for Profile model.

class Profile < ActiveRecord::Base   
  belongs_to :user  
end

Now I have basic Profile for a User which was created at sign up. Now how do I go about editing user profile using the helper device provides current_user with form_for?


Solution

  • We did something like this:

    #app/models/user.rb
    Class Model < ActiveRecord::Base
        before_create :build_profile
    end
    

    This populates the profile record in the database, allowing you to update it later on

    Once you've saved the user, you will be best using accepts_nested_attributes_for to populate & save profile options through a form for the user, like this:

    #config/routes.rb
    resources :users do
       resources :profiles 
    end
    
    #app/views/profiles/edit.html.erb
    <%= form_for @profile do |f| %>
         <%= f.hidden_field :user_id, current_user.id %>
         <%= f.text_field :your_profile_options %>
    <% end %>
    

    This is a very basic way to do it, but hopefully will give you more ideas. If you want to see this in the wild, check out http://video-conference-demo.herokuapp.com (it uses Devise to handle users & has extra "profile" model too)