Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Choosing Between belongs_to and has_one

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 374
    Comment on it

    If we have has_one relation between two models then we need to declare belongs_to relation in one model and has_one relation in another model. belongs_to will be declared in the model where we will have the foreign_key and has_one in the other model . Generally has_one relation is used where we need to define possession like User has one Wallet.

    We can add the relation like this:

    class User < ActiveRecord::Base
      has_one :wallet
    end
    
    class Wallet < ActiveRecord::Base
      belongs_to :user
    end
    
    

    The corresponding migration might look like this:

    class CreateUsers < ActiveRecord::Migration
      def change
        create_table :users do |t|
          t.string  :name
          t.timestamps
        end
    
      end
     end
    class CreateWallets < ActiveRecord::Migration
      def change
        create_table :wallets do |t|
          t.integer :user_id
          t.integer :amount
          t.timestamps
        end
      end
     end
    

    Instead of t.integer :user_id we can also write t.references :user

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: