First of all, I'm fairly new to Ruby, Rails and ActiveRecord, so detailed answers would be very appreciated.
What I'm trying to achieve is a model with a Many-to-Many relation to itself. It's basically a "user has many friends (aka users)" setup.
This is what I currently have for my tables:
create_table "friendships" do |t|
t.integer "user_id"
t.integer "friend_id"
end
create_table "users" do |t|
t.string "email",
t.string "username",
# etc.
end
And this is what I have for my models:
class Friendship < ActiveRecord::Base
belongs_to :user
belongs_to :friend, class_name: "User"
end
class User < ActiveRecord::Base
has_many :friendships
has_many :friends, through: :friendships
end
From what I've been reading, this should be giving me what I want. However, when I try to access .friends
on the User
object I receive an uninitialized constant Friend
error.
I searched for a while without luck. I really don't know how to tackle this issue, it must be something simple that I missed.
I'm using Rails 4.0.1 on Ruby 2.0.0p247 if it helps.