Pavlin
Pavlin

Reputation: 5528

Rails 4 define association on different table

I am using Rails 4.2.5 and I'm having a bit of trouble figuring out the ActiveRecord associations.

I've got the following table:

+-----------------+
| FRIEND_REQUESTS |
+-----------------+
| id              |
| user_id         |
| target_user_id  |
+-----------------+

I want to define the associations in such a way so that I can access them like this:

@user.friend_requests
@user.incoming_friend_requests

This is what I've got so far:

class User < ActiveRecord::Base
  has_many :friend_requests
  has_many :incoming_friend_requests,
    class_name: 'FriendRequest',
    foreign_key: 'target_user_id'
end

class FriendRequest < ActiveRecord::Base
  belongs_to :user
  has_one :target_user, class_name: 'User'
end

but this returns the following error when trying to access incoming_friend_requests (the regular friend_requests work fine):

SQLException: no such column: users.friend_request_id: SELECT  "users".* FROM "users" WHERE "users"."friend_request_id" = ? LIMIT 1

I've also tried setting the :incoming_friend_requests to the following

has_many :incoming_friend_requests,
    class_name: 'FriendRequest',
    inverse_of: :target_user

but nothing seems to be working. I'm aware that I could easily put together a SQL query to find the incoming friend requests for a user, but I'm only just getting started with Rails, and I would really like to figure this out using just ActiveRecord associations.

It seems to me that should be looking at the friend_requests table to find the foreign keys, but I haven't been able to find a parameter to pass to has_many that would change what table it should check.

Any help would be appreciated.

Upvotes: 0

Views: 105

Answers (2)

romainsalles
romainsalles

Reputation: 2143

If target_user_id is a column from the FRIEND_REQUESTS table, you should write :

class FriendRequest < ActiveRecord::Base
  belongs_to :user
  belongs_to :target_user, class_name: 'User', :foreign_key => "target_user_id"
end

Upvotes: 2

Pavlin
Pavlin

Reputation: 5528

I've found the problem, I was using the wrong type of association on the friend requests model and some missing foreign key parameters.

A working version looks like this:

class User < ActiveRecord::Base
  has_many :friend_requests, foreign_key: 'user_id'
  has_many :incoming_friend_requests,
    class_name: 'FriendRequest',
    foreign_key: 'target_user_id'
end

class FriendRequest < ActiveRecord::Base
  belongs_to :user, foreign_key: 'user_id'
  belongs_to :target_user,
    class_name: 'User',
    foreign_key: 'target_user_id'
end

Upvotes: 0

Related Questions