automatically create ActiveRecord parent for association

66 views Asked by At

In my app i have:

class Wallet < ActiveRecord::Base
  belongs_to :owner, :polymorphic => true
  has_many   :transactions, :class_name => 'WalletTransaction'
end

class WalletTransaction < ActiveRecord::Base
  belongs_to :wallet
end

class User < ActiveRecord::Base
  has_one    :wallet, :as => :owner
  has_many   :wallet_transactions, :through => :wallet, :source => :transactions
end

How do I automatically create a Wallet for a User who has none when a WalletTransaction is added for that User. Example:

@user = User.find(1)
@wallet_transaction = @User.wallet_transactions.new(attributes)

If the above code is run and the student has no Wallet record in the database, the app should automatically create one.

1

There are 1 answers

2
Vu Minh Tan On

You can use first_or_create:

@wallet_transaction = @user.wallet_transactions.first_or_create(attributes)

UPDATE: I misunderstood the question, you should create the wallet first if none exists and then refer to the transactions through the @wallet instance. Doing so also ensures that the wallet_id of WalletTransaction is always referred to the correct wallet.

@wallet = @user.wallet.first_or_create
@wallet_transaction = @wallet.transactions.new(attributes)