开发者

Rails: Should I use has_many :through?

开发者 https://www.devze.com 2023-02-28 08:38 出处:网络
I\'m trying to figure out how to best way to create associations for the following models: User Category

I'm trying to figure out how to best way to create associations for the following models:

  • User
  • Category
  • Post
  • Comments

Here are the requirements I'm trying to meet:

  • A user can have many posts
  • A post belongs to a user
  • A post can have many comments
  • A comment belongs to a post
  • A post can belong to a category
  • A user does NOT have many categories. (The number of categories is fixed and the same for all users)
  • A category can have many posts

In terms of routing, I'd like to be able to access a post within a certain category for a specific user. For example:

http://domain.com/users/1/categories/1/posts

Since there is no direct relationship between User and Category, I'm not quite sure how to best set up the associations. And I'm totally lost on how to configure the routes.

Here's what I开发者_运维知识库 have for my models:

class User < ActiveRecord::Base
  has_many :posts
end

class Category < ActiveRecord::Base
  has_many :posts
end

class Post < ActiveRecord::Base
  belongs_to :user
  belongs_to :metric
  has_many :comments
end

class Comments < ActiveRecord::Base
  belongs_to :post
end

Is this a case where I should be using has_many :through relationships? Or something more complex like polymorphic associations? Thanks in advance!


Yes, it would be a very good idea to use :

User has_many :comments, :through => :posts

If you like, you can also get categories comments, by :

Category has_many :comments, :through => :posts 

Remember that a through association is just a facility that allows you to do things like user.comments directly (and through is the way for the association to find the user comment that is referred to post model).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号