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.
You can use
first_or_create
: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.