Rails多对多有条件添加新条件

时间:2011-07-26 22:17:36

标签: ruby-on-rails activerecord has-many-through has-and-belongs-to-many

我正在使用“喜欢”和“推荐”为用户和电影建模。

模型如下:

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

用一张表来映射关系:

 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

现在我在尝试

时遇到错误
u = User.first
m = Movie.first
u.movie_liked << m 

出现以下错误

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'))

任何想法我都可以很好地构建它,所以我可以使用&lt;&lt;操作员,它会自动分配正确的类型吗?

谢谢!

1 个答案:

答案 0 :(得分:1)

您可以创建RecommendationLike模型,并使用它们加入带电影的用户。或者只是一个名为不知道如何(RecommendLike?)的模型,如果你真的希望保存在一个表上。然后:

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