简体   繁体   English

关于Rails协会的问题

[英]question about rails associations

consider this code 考虑这个代码

class User < ActiveRecord::Base
  has_many :views
  has_many :posts, :through => :views, :uniq => true

  has_many :favorites
  has_many :posts, :through => :favorites, :uniq => true

  has_many :votes
  has_many :posts, :through => :votes, :uniq => true
end

# controller code

user = User.find(3)
posts = user.posts # ??

that said i have established three relationships between posts and users, through different way. 那就是说我通过不同的方式在帖子和用户之间建立了三种关系。 But what about the last line??? 但是最后一行呢? how can I tell rails that I want to get the posts through views or favorites. 如何告诉Rails我想通过视图或收藏夹获取帖子。

You can give each association a different name, but point it at the same model using the :class_name option. 您可以为每个关联指定不同的名称,但可以使用:class_name选项将其指向相同的模型。 Like so: 像这样:

class User < ActiveRecord::Base
  has_many :views
  has_many :view_posts, :through => :views, :class_name => 'Post', :uniq => true, 

  has_many :favorites
  has_many :favorite_posts, :through => :favorites, :class_name => 'Post', :uniq => true

  has_many :votes
  has_many :vote_posts, :through => :votes, :class_name => 'Post', :uniq => true
end

# Then...
User.find(3).favorite_posts

You may also find named_scope useful. 您可能还会发现named_scope有用。

You have to give the associations different names. 您必须为协会指定其他名称。 The 2nd and 3rd has_many :posts just overwrite the previous ones. 第二和第三has_many :posts覆盖了以前的。 You will need something like has_many :view_posts , has_many :favorite_posts , etc. 您将需要诸如has_many :view_postshas_many :favorite_posts东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM