I solved the problem, see my answer below for the fully functional relationships, models, and schema.
In testing my friendship model, I'm running into an error:
ActiveRecord::StatementInvalid:
SQLite3::SQLException: no such column: users.user_id: SELECT 1 AS one FROM "users" INNER JOIN "friendships" ON "users"."id" = "friendships"."friend_id" WHERE "friendships"."user_id" = ? AND "users"."user_id" IN (SELECT "friendships"."id" FROM "friendships" WHERE "friendships"."status" = ?) AND "users"."id" = ? LIMIT 1
while trying to access a users pending_friends in an rspec test after creating a friendship. I have the following code that defines a friendship:
class Friendship < ActiveRecord::Base
belongs_to :user
belongs_to :friend, :class_name => "User"
enum status: [:pending, :accepted]
scope :accepted, -> { where(status: :accepted) }
scope :pending, -> { where(status: :pending) }
validates :user, uniqueness: { scope: :friend, message: "This user is already your friend" }
def decline
self.destroy
end
def accept
self.update status: :accepted
end
end
The code below defines what pending_friends should be in my user model:
has_many :friendships
has_many :pending_friends, -> { where(friendships: Friendship.pending) },
through: :friendships, class_name: "User", source: :friend
I'm unsure why it's trying to access users.user_id... If anyone knows how I can fix this any help would be greatly appreciated, I've been digging into how joins work but I can't seem to find anything helpful.
FYI: This is how I'm creating the friendship:
friendship1 = Friendship.build(user: current_user, friend: other_user)
friendship2 = Friendship.build(user: other_user, friend: current_user)
(and then a save and error checking)
This is my friendship migration:
class CreateFriendships < ActiveRecord::Migration
def change
create_table :friendships do |t|
t.integer :status, :null => false, :default => 0
t.integer :user_id
t.integer :friend_id
t.timestamps null: false
end
end
end