Rails中的关系类型

嗨,我是非常新的轨道,需要一些帮助,没有什么类似我能找到的,我看着类似线路上的所有轨道演员。

所以我有一个文章模型和用户模型(设计)。

我想用户在Follow Mode或Just Read Later Mode中添加文章。

所以UserArticleAssociation有article_id,user_id和关联类型。 我不明白如何正确实现此function。 我可以做一些黑客来做这些,但我不想。

任何类似的教程都会有很大的帮助。

试试这个:

class User < ActiveRecord::Base has_many :user_articles has_many :read_user_articles, :class_name => "UserArticle", :conditions => {:mode => "read"} has_many :follow_user_articles, :class_name => "UserArticle", :conditions => {:mode => "follow"} has_many :articles, :through => :user_articles has_many :read_articles, :through => :read_user_articles, :source => :article has_many :follow_articles,:through => :follow_user_articles,:source => :article end # Add a column called mode of type string (follow, read) class UserArticle < ActiveRecord::Base belongs_to :user belongs_to :article end class Article < ActiveRecord::Base has_many :user_articles has_many :read_user_articles, :class_name => "UserArticle", :conditions => {:mode => "read"} has_many :follow_user_articles, :class_name => "UserArticle", :conditions => {:mode => "follow"} has_many :readers, :through => :read_user_articles, :source => :user has_many :followers,:through => :follow_user_articles,:source => :user end 

现在您可以执行以下操作:

要添加文章以阅读/关注类别:

 user.read_articles << article user.follow_articles << article 

要么

 article.reader << user article.follower << user 

访问文章

 user.read_articles user.follow_articles 

访问用户

 article.readers article.followers 

你应该使用has_many:通过关联。 这里有一个关于它的Railscast: http ://railscasts.com/episodes/47-two-many-to-many