首页 > 解决方案 > 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:帐户的未定义方法事务

标签: ruby-on-railshas-many-through

解决方案


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_idt.string :account_name. 一般来说,我只使用 _id 作为外键。


推荐阅读