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)