【发布时间】:2020-04-03 14:14:40
【问题描述】:
我正在尝试创建以下内容:
模型:用户、帐户、交易 逻辑:用户有多个帐户。帐户有许多交易。用户通过账户进行了多次交易。
模型
class User < ApplicationRecord
has_many :accounts
has_many :transactions, :through => :accounts
End
class Account < ApplicationRecord
belongs_to :user
has_many :transactions
end
class Transaction < ApplicationRecord
belongs_to :account
end
迁移
class CreateUsers < ActiveRecord::Migration[5.0]
def change
create_table :users do |t|
t.string :name
t.timestamps
end
end
end
class CreateAccounts < ActiveRecord::Migration[5.0]
def change
create_table :accounts do |t|
t.string :account_id
t.belongs_to :user, index:true
t.timestamps
end
end
end
class CreateTransactions < ActiveRecord::Migration[5.0]
def change
create_table :transactions do |t|
t.string :account_id
t.decimal :amount, :precision => 8, :scale => 2
t.belongs_to :account, index:true
t.timestamps
end
end
end
我可以使用以下代码为用户创建帐户:
user = User.create(name: "John")
user.accounts.create(account_id: "123")
但是当涉及到交易时,使用相同的逻辑:
user = User.create(name: "John")
user.accounts.create(account_id: "123")
accounts.transactions.create(account_id: "123", amount: 10)
我收到一个错误
NoMethodError: Account 的未定义方法交易
【问题讨论】:
-
不应该是单个
account而不是accounts为其创建交易吗?
标签: ruby-on-rails has-many-through