我试图用一些值为我的数据库设定种子。类型用户,帐户和事务是ActiveRecord对象。成功创建了两个用户,并成功创建了这些用户的两个帐户。当我尝试在第二个块中执行相同的操作时,它会告诉我NoMethodError: undefined method 'transactions' for #<Array:0x0000000734d198>
,即使第二个块内的放置显示该帐户实际上是#。
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
这是account.rb文件,其中transaction被定义为has_many关系:
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
我不知道发生了什么事。在Account上,交易肯定被定义为has_many。导致此错误的原因是什么?我对红宝石很新。
答案 0 :(得分:1)
当你写
时accounts << user.accounts.create!([{:account_type => 'SAVINGS'}])
以上,您创建的不是一个帐户,而是一个包含单个帐户的数组。然后,当你说
transactions << account.transactions.create!([{:transaction_type => 'WITHDRAWAL', :amount => 500, :expires_at => Time.now + 1.day, :fulfilled => false}])
rails认为您正在尝试使用数组中的方法#transactions
,这显然无法完成,因为数组没有这样的方法。