Search code examples
ruby-on-railsrubymodelsrelationship

Construct relationship in models in rails and Insert data into it


How to construct a model in rails 3

  1. user having one profile.

  2. user having one notification

  3. user having one role such as admin etc.

I want to make their relation ship. After making it.

How to use one form to insert data into all these tables at a time.

Any help will be appriciated.. Thank you


Solution

  • search http://guides.rubyonrails.org/association_basics.html to better understand rails associations.

    user.rb

    has_one :profile
    has_one :notification
    has_one :role
    
    accepts_nested_attributes_for :profile, :notification, :role
    

    You might to put each of the "accepts nested attributes for" on their own line.

    The each other model would need:

    belongs_to :user

    EDIT

    form

    = form_for @user do |f|
    
     .field
       f.text_field :name
    
     .field
       f.text_field :email
    
     f.fields_for :profile do |t|
       .field
         t.text_field :description
    
     .actions
       = f.submit
    

    Also, in your controller, make sure to have:

    def new
     @user = User.new(profile: Profile.new)
    end