Accessing more than one active records in action controller in rails 3

151 views Asked by At

suppose I have 2 models: 1. user and 2. userProfile
we have one-to-one relationship between 2 models.
Then,I would like to create Usercontroller and create user with fields such as username and password in user and other details like address, mobile number,etc in userprofile.
user_id is a foreign key in user_profile
Then I created new.html.erb in user a view that render all above fields in a same form. Then how I can save the data in two different tables user and userprofile respectively.

what I tried is
1. has_one :user_profile in user.rb and belongs_to :user in user_profile.rb
2. accepts_nested_attributes_for :user_profile in user.rb user_controller:



     def create
       @user = User.new(params[:user])
       if @user.save
          @userprofile = @user.create_user_profile(params[:user_profile])
               redirect_to root_url, :notice => "Signed up!"     
       else
          render "new"
        end 
      end

 

3. Then I got error the only userid is created in user_profile and also update run to make user_id nil which can't be! so raising error:
Unknown column 'user_profiles.' in 'where clause': UPDATE `user_profile` 
SET `user_id` = NULL WHERE `user_profiles`.`` IS NULL
so what's wrong and how to troubleshoot this?

1

There are 1 answers

7
jstr On

If you're using accepts_nested_fields_for then you don't need to manage saving the UserProfile records yourself. ActiveRecord will take care of it for you.

To get this to work you need to:

  1. Make sure you have accepts_nested_fields_for :user_profile in your User model
  2. Update your app/views/users/_form.html.erb to include form elements for the UserProfile, e.g.:

    <%= f.fields_for :user_profile, @user.user_profile do |profile_form| %>
    <%= profile_form.text_field :address %>
    <%= profile_form.text_field :mobile_number %>
    <% end %>
    
  3. Update your UsersController#new action to build the UserProfile for the User, e.g.

    def new
      @user = User.new
      @user.build_user_profile
      (...)
    end
    

For more information see the Rails API docs covering Active Record Nested Attributes.