Nested forms with associations

You can create nested forms according to entity relationships and rails framework will take care of saving data in db.  So lets start with example:

 

Taking Example of  User and Profile

User has login information of user  [email: stirng and password:string], and Profie has user details [name , age, mobile etc]

User < ActiveRecord::Base

    has_one :profile

end

Profile < ActiveRecord::Base

     belongs_to :user

end

We can make a single nested form which will save data in both

View:

<!-- This is simple form without classes you can add css classes and div to make it beautiful -->

<%= form_for(@user) do |f| %>

    Email: <%= f.input :email %> <br/>

    Password: <%= f.password_field :password %> <br/>

     <!-- Now creating fields for profile -->

    <%= f.fields_for :profile do |pf| %>

        Name:   <%= pf.input :name %> <br/>

        Age:      <%= pf.input :age %> <br/>

       Mobile:  <%= pf.input :mobile %> <br/>

   <% end %>

    <%= f.submit  %>

<% end %>

Controller:

def new

    @user = User.new

    @user.build_profile

end

# Need to add profile_attributes for acceptence

def user_params

    params.require(:user).permit(:email, :password, profile_attributes: [:name, :age, :mobile])

end

Model:

User < ActiveRecord::Base

    has_one :profile

# To accept nested attributes we need to add below function

   accepts_nested_attributes_for :profile

end

 

Now if you will submit this form a user will create and user_id will save in profile with profile info

You can do same for has_many relationships

 

Thanks for reading.........

Comments