我正在尝试用一些值来为我的数据库做种。类型 User、Account 和 Transaction 是 ActiveRecord 对象。成功创建了两个用户,并成功创建了这些用户的两个帐户。当我尝试在第二个 block 中做同样的事情时,它告诉我 NoMethodError: undefined method 'transactions' for #<Array:0x0000000734d198>
,即使第二个 block 中的 puts 显示该帐户实际上是 #。
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 文件,其中交易被定义为 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
我不知道发生了什么。 transactions 明确定义为 has_many on Account。是什么导致了这个错误?我对 ruby 很陌生。
最佳答案
当你写的时候
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
,这显然无法完成,因为数组没有这样的方法。
关于ruby-on-rails - 运行 db :seed 时数组的未定义方法 'transactions',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40824182/