Rohan Mayya
Rohan Mayya

Reputation: 206

referencing foreign key attributes rails

I have a scaffold VirtualTransaction referencing my User model.

virtual_transaction.rb

class VirtualTransaction < ApplicationRecord
  has_one :buyer, :class_name => 'User', :foreign_key => 'buyer_id'
  has_one :seller, :class_name => 'User', :foreign_key => 'seller_id'
end

user.rb

class User < ApplicationRecord
  has_many :virtual_transactions
end

But I can't take any further steps to access the association.

I get:

ActiveRecord::StatementInvalid: PG::UndefinedColumn: ERROR:  column 
users.buyer_id does not exist
LINE 1: SELECT  "users".* FROM "users" WHERE "users"."buyer_id" = $1...
: SELECT  "users".* FROM "users" WHERE "users"."buyer_id" = $1 LIMIT $2
from (irb):7

when I try to do:

virtual_transaction=VirtualTransaction.first
virtual_transaction.buyer

All I intend to do is access the name of the user referencing the buyer/seller id and display it in my view.

VirtualTransaction(id: integer, buyer_id: integer, seller_id: integer, amount: decimal, created_at: datetime, updated_at: datetime) 

Upvotes: 0

Views: 344

Answers (2)

Tom Aranda
Tom Aranda

Reputation: 6036

I think you should use belongs_to instead of has_one as your association. That will cause ActiveRecord to look for the buyer_id foreign key in the virtual_transactions table:

class VirtualTransaction < ApplicationRecord
  belongs_to :buyer, :class_name => 'User', :foreign_key => 'buyer_id'
  belongs_to :seller, :class_name => 'User', :foreign_key => 'seller_id'
end

Upvotes: 1

Ronan Lopes
Ronan Lopes

Reputation: 3380

You're using buyer_id as your table column to store the reference, and postgresql can't find that column. I don't know your table structure, but you can add a column for foreign key in that case like this:

rails g migration AddBuyerIdToVirtualTransaction buyer_id:integer

Also, you said your scaffold is called VirtualTransaction, but in the piece of code you pasted, the class is name only Transaction.

I think you doing some mistake with the names of your tables/columns. If you post more details about that, we could help better. Good luck

Upvotes: 0

Related Questions