Search code examples
ruby-on-railsruby-on-rails-3postgresqlpg

Problems with belongs_to condition in model


I'm making personal money management app. There I have 2 models: Account and Transaction. Transaction has belongs_to :account and Account has has_many :transactions.

When I had account_id column in db (postgres) everything worked fine. But I have to rename account_id to from_account_id and add another column to_account_id. So that I can add a spending from Account and income to Account. Also it's necessary for transfers between accounts (where from_account_id and to_account_id both will have some values).

So, I've renamed fields :account_id in my views to :from_account_id and add :to_account_id field. But, when I rename account_id to from_account_id in db, I've got this error.

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

My Pages#index controller is:

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

I think Rails is trying to find account_id column in transactions table, because Transaction belongs_to :account. But I need both columns for :account to and from, as you see. So, maybe I need to change this belongs_to condition in Transaction model, but I don't know how.

Thanks for any ideas!


Solution

  • You have to define two belong_to relations in your Transaction class, one for each column in your table 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
    

    See options in Rails Relation Guide