我正在尝试创建以下内容:
模型:用户,帐户,交易逻辑:用户有多个帐户。帐户有很多交易。用户通过帐户有很多交易。
模型
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:帐户的未定义方法事务
class CreateTransactions < ActiveRecord::Migration[5.0]
def change
create_table :transactions do |t|
t.string :account_id
t.belongs_to :account, index:true
end
end
end
belongs_to:account将创建一个名为account_id的列,但是您在上面的行中已经具有account_id。将t.string :account_id
更改为t.string :account_name
。通常,我只将_id用于外键。
我这里有几个问题,
在帐户和交易中,您都有一个字符串列account_id。在交易中,默认情况下,帐户的外键也将是account_id?
所以您可能必须为此保留一个差异名称。
并且您正在调用accounts.transactions,每个帐户有很多交易,因此应该在单个帐户对象上调用交易。(Accounts.last.transactions等)
而且我看不到在任何地方定义帐户(我假设您没有发布该部分代码。)