Relationship Type in Rails
Hi I am very new rails 开发者_开发知识库, would need some help , there is nothing similar I could find , i watch all the rail casts on the similar lines.
So I have a article model and user model ( devise ) .
I would to user to add article either in Follow Mode or Just Read Later Mode.
so UserArticleAssociation has article_id , user_id and association type . I am not understanding how to implement this feature correctly. I could make some hack to do these , but I don't want to.
Any tutorial on similar will be great help.
Try this:
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
Now you can do the following:
To add an article to read/follow category:
user.read_articles << article
user.follow_articles << article
OR
article.reader << user
article.follower << user
To access the articles
user.read_articles
user.follow_articles
To access the users
article.readers
article.followers
You should use has_many :through association. There is a Railscast about it here: http://railscasts.com/episodes/47-two-many-to-many
精彩评论