CanadaIT CanadaIT - 7 days ago 6
Ruby Question

Undefined method 'transactions' for array when running db:seed

I am trying to seed my database with some values. Types User, Account, and Transaction are ActiveRecord objects. Two users are created successfully and two accounts on those users are created successfully. When I try to do the same thing in the second block, it tells me

NoMethodError: undefined method 'transactions' for #<Array:0x0000000734d198>
, even though a puts inside the second block shows that account is in fact a #.

require 'securerandom'

Account.destroy_all
Branch.destroy_all
Terminal.destroy_all
Transaction.destroy_all
User.destroy_all


users = User.create!([
{
:name => 'Bob Rob',
:email => 'br@gmail.com'
}, {
:name => 'Frank Krawlin',
:email => 'krawlin@gmail.com'
}
])

puts users

accounts = []
users.each do |user|
accounts << user.accounts.create!([{:account_type => 'SAVINGS'}])
end

puts accounts

transactions = []
accounts.each do |account|
transactions << account.transactions.create!([{:transaction_type => 'WITHDRAWAL', :amount => 500, :expires_at => Time.now + 1.day, :fulfilled => false}])
end

puts transactions

branches = Branch.create!([{:address => '215 Oxford St W, Toronto, ON'}])

terminals = []
branches.each do |branch|
rand(1..4).times do
terminals << branch.terminals.create!([{:token => SecureRandom.uuid}])
end
end


Here is the account.rb file where transactions is defined as a has_many relationship:

class Account < ApplicationRecord
belongs_to :user
has_many :transactions

validates :account_type, inclusion: {in: %w(CHEQUING SAVINGS),
message: "%{value} is not a valid account type"}

before_validation :correct_case

protected
def correct_case
self.account_type.upcase!
end
end


I have no idea what is going on. transactions is definitely defined as has_many on Account. What is causing this error? I am very new to ruby.

Answer

When you wrote

accounts << user.accounts.create!([{:account_type => 'SAVINGS'}])

above, you created not a single account, but an array with a single account. Then, when you say

transactions << account.transactions.create!([{:transaction_type => 'WITHDRAWAL', :amount => 500, :expires_at => Time.now + 1.day, :fulfilled => false}])

rails thinks you are trying to use a method #transactions from an array, which obviously can't be done, since array has no such method.

Comments