Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails has_one with class name and foreign key

I have a Rails model which I use two has_one relations: requesterand friend. When in the console I use:

f = FriendRequest.all
f[0].requester

I get ActiveRecord::StatementInvalid: SQLite3::SQLException: no such column: users.requester_id: SELECT "users".* FROM "users" WHERE "users"."requester_id" = 4 LIMIT 1 .

I don't really know how to specify a `has_one' relationship with a class name and a key which specifies the record. This is my model:

class FriendRequest < ActiveRecord::Base
  has_one :requester, :class_name => "User", :foreign_key => "requester_id"
  has_one :friend, :class_name => "User", :foreign_key => "friend_id"
end

How could I do it? In a belongs_to relationship I use the same, obviously replacing has_onewith belongs_to. Thanks!

like image 989
pmerino Avatar asked May 19 '12 11:05

pmerino


1 Answers

has_one :requester, :class_name => "User", :foreign_key => "requester_id"

This line (from the code that you posted) indicates that the requester is a User, and the table users should contain a column requester_id that is the foreign key toward friend_requests records. The rails error message states that the column requester_id does not exists (you have to create it via a migration).

In this case, use

rails generate migration AddRequesterIdToUsers requester_id:integer

It will generate the migration:

class AddRequesterIdToUsers < ActiveRecord::Migration
  def change
    add_column :users, :requester_id, :integer
  end
end  

And run them migration with rake db:migrate.

Look at the Rails Relation Guide for more information on differences between has_one and belongs_to, and how to use them.

like image 122
Baldrick Avatar answered Oct 22 '22 15:10

Baldrick