2011-05-13 87 views
0

嗨,我很新的铁轨,需要一些帮助,没有什么类似的我可以找到,我看着所有的铁路线上的类似线路。关系类型在轨道

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

我想用户在Follow模式或Just Read Later模式下添加文章。

所以UserArticleAssociation有article_id,user_id和关联类型。我不了解如何正确实现此功能。我可以做一些破解,但我不想。

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

+0

什么是UserArticleAssociation?这是一个模型吗?你能发布代码来显示交互吗? – 2011-05-13 19:15:58

回答

1

试试这个:

添加了一篇文章,读/如下类别:

user.read_articles << article 
user.follow_articles << article 
以下

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 

现在你可以做

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

要访问的文章

user.read_articles 
user.follow_articles 

访问用户

article.readers 
article.followers 
+0

谢谢你会尝试这:)如果你解释这是干什么和如何做,会很好。 – 2011-05-13 20:47:03

+0

user.read_articles <<文章这是伟大的控制台,但我如何做到这一点,我们可以有其他方面的功能,如user.read_articles,article.readers,article.followers – 2011-05-13 21:41:42

+0

你已经有user.read_articles。添加article.readers和article.followers是非常直接的,只需按照User类中指定的约定。 – 2011-05-14 00:05:58