ruby-on-rails - Rails has_many 通过特定的 id
问题描述
我正在尝试创建以下内容:
模型:用户、账户、交易 逻辑:用户有很多账户。帐户有许多交易。用户通过帐户进行了许多交易。
楷模
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 作为外键。
推荐阅读
- c++ - 在输入向量的笛卡尔积中创建第 n 个元素的元组
- html - h3 和锚定内联块(在同一行)
- python - TKinter 处理多显示器和图像显示
- python - 对于 Python 中另一个列表的每个不同值,计算一个列表的最大值和最小值的最佳方法是什么?
- javascript - React .map 不重新渲染
- sql-server - 没有 Azure 订阅,无法创建集成服务目录
- c++ - 将整数分配给 char * 指针数组中的索引
- python-3.x - 更新条目小部件实时 tkinter
- android - 使用 Firebase 时无法计算儿童数量
- android - 以编程方式将 MenuItem 添加到 Group 不会添加单选按钮