考虑一下:
class User < ActiveRecord::Base
# name, email, password
end
class Article < ActiveRecord::Base
# user_id, title, text
end
class Favorites < ActiveRecord::Base
# user_id, article_id
end
如何以@ user.articles(用户创建的文章)和@ user.favorite_articles(收藏模型中最喜欢的文章)的方式将所有这些组合在一起
提前致谢!
答案 0 :(得分:1)
如果我理解你想要的东西,我会说
class User < ActiveRecord::Base
has_many :articles
has_many :favorite_articles, :through => :favorites, :source => :article
end
class Article < ActiveRecord::Base
has_and_belongs_to_many :user
end
class Favorites < ActiveRecord::Base
has_and_belongs_to_many :user
has_one :article
end
编辑:添加了favorite_articles
答案 1 :(得分:1)
您可以使用has_many :through
关联从用户那里获取喜爱的文章。您还可以使用它来获取喜欢给定文章的用户。
class User < ActiveRecord::Base
has_many :articles
has_many :favorites
has_many :favorite_articles, :through => :favorites, :source => :article
end
class Article < ActiveRecord::Base
belongs_to :user
has_many :favorites
has_many :favorited_by_users, :through => :favorites, :source => :user
end
class Favorite < ActiveRecord::Base
belongs_to :article
belongs_to :user
end