Reputation: 8060
I am modelling users and movies with "liked" and "recommeded".
The models are as follows:
class Movie < ActiveRecord::Base
attr_accessible :title, :imbd_id
has_and_belongs_to_many :liked_by, :class_name => "User",
:conditions => { "type" => "like" }
has_and_belongs_to_many :recommended_by, :class_name => "User",
:conditions => { "type" => "recommend" }
end
class User < ActiveRecord::Base
has_and_belongs_to_many :movies_liked, :class_name => "Movie",
:conditions => { "type" => "like" }
has_and_belongs_to_many :movies_recommended, :class_name => "Movie",
:conditions => { "type" => "recommend" }
end
with one table to map the relationship:
create_table "movies_users", :id => false, :force => true do |t|
t.integer "user_id"
t.integer "movie_id"
t.string "type" # this can be "like" or "recommend"
t.string "status_id"
t.datetime "created_at"
t.datetime "updated_at"
end
Now I am getting an error when I try to do
u = User.first
m = Movie.first
u.movie_liked << m
with the following error
ruby-1.9.2-p290 :003 > u.movies_tweeted << m
ActiveRecord::StatementInvalid: SQLite3::SQLException: no such column: movies.type: SELECT * FROM "movies" INNER JOIN "movies_users" ON "movies".id = "movies_users".movie_id WHERE ("movies_users".user_id = 1 AND ("movies"."type" = 'like'))
Any idea I can structure it nicely so I can just use the << operator and it will automatically assign the correct type?
Thanks!
Upvotes: 0
Views: 263
Reputation: 3766
You can create Recommendation
and Like
models and use them to join the Users with Movies. Or just a single model called don't know how(RecommendLike
?), if you really wish to save on one table. And then:
User
has_many :recommendations
has_many :movies_recommended, :class_name => "Movie", :through => :recommendations
has_many :likes
has_many :movies_liked, :class_name => "Movie", :through => :likes
Upvotes: 1