我正在制作个人理财应用程序。我有2个模型:Account
和Transaction
。
Transaction
有belongs_to :account
,Account
有has_many :transactions
。
当我在db(postgres)中有account_id
列时,一切正常。但我必须将account_id
重命名为from_account_id
并添加另一列to_account_id
。这样我就可以将Account
和收入增加到Account
。此外,帐户之间的转帐也是必要的(其中from_account_id
和to_account_id
都有一些值。)
因此,我已将观看中的字段:account_id
重命名为:from_account_id
并添加:to_account_id
字段。但是,当我在db中将account_id
重命名为from_account_id
时,我遇到了这个错误。
ActiveRecord::StatementInvalid in PagesController#index
PG::Error: ERROR: column transactions.account_id does not exist
LINE 1: ...s".* FROM "transactions" INNER JOIN "accounts" ON "transacti...
^
: SELECT "transactions".* FROM "transactions" INNER JOIN "accounts" ON
"transactions"."account_id" = "accounts"."id" WHERE "accounts"."user_id" = 17 ORDER BY
transactions.date DESC
我的Pages#index
控制器是:
class PagesController < ApplicationController
def index
if user_signed_in?
@accounts = current_user.accounts.all
@transaction = current_user.transactions.build
@transactions = current_user.transactions.all
@categories = current_user.categories.all
end
end
end
我认为Rails正试图在account_id
表中找到transactions
列,因为Transaction
belongs_to :account
。但正如您所见,我需要:account
to
和from
两个列。所以,也许我需要在belongs_to
模型中更改此Transaction
条件,但我不知道如何。
感谢您的任何想法!
答案 0 :(得分:1)
哟必须重命名has_many
模型中的Account
关系。像下面这样的东西会起作用:
has_many :transactions, :foreign_key => "from_account_id"
答案 1 :(得分:1)
您必须在belong_to
课程中定义两个Transaction
关系,表格transactions
中每列一个:
class Transaction < ActiveRecord::Base
belongs_to :from_account, :class_name => 'Account', :foreign_key => 'from_account_id'
belongs_to :to_account, :class_name => 'Account', :foreign_key => 'to_account_id'
# ...
end
中的选项