I'm trying to implement a "facebook like" like relationship. I wanted to use inheritance for that, so here's my structure :
Likes with a user_id:integer attribute |> PostsLike that inherits Like with a post_id:integer attribute
So here's my Like.rb model :
class Like < ActiveRecord::Base
belongs_to :user
end
And then my PostLike.rb model :
class Postlike < Like
belongs_to :post
end
And finally I have a post model that will have multiple postlikes objects :
class Post < ActiveRecord::Base
has_many :postlikes
end
But here's my problem, when I go into irc and that :
I get a Post object :
ruby-1.9.2-p290 :001 > @p = Post.all.first
I try to get postlikes of this object, here's the sql statement :
SELECT likes
.* FROM likes
WHERE likes
.type
IN ('Postlike') AND likes
.post_id
= 310
So basically instead of doing
postlikes.post_id
Rails' doing
likes.post_id
Any idea to fix that ?
ActiveRecord stores Like and Postlike object in the same table named "likes", and uses a column named "type" to save the class of the object. That explains the statement:
WHERE likes.type IN ('Postlike') AND likes.post_id = 310
There is no table postlikes
See "Single table inheritance" chapter at http://api.rubyonrails.org/classes/ActiveRecord/Base.html