开发者

What is the relationship between these two tables in RoR?

开发者 https://www.devze.com 2023-01-07 21:19 出处:网络
I am developing an application like the stackoverflow, which questions or articles have at less one tag. And one tags must have one or more articles.

I am developing an application like the stackoverflow, which questions or articles have at less one tag. And one tags must have one or more articles.

So, I am doing this in migration in RoR. I am consider which relationship is suitable for both table. In article table, should use a "has_many", and in the tag table, should use "has_many". But I am thinking is it necessary to add one more table in the middle, something like....

So, the first one is like that:

class Article < ActiveRecord::Base
  has_many :tags
end

class Tag < ActiveRecord::Base
  has_many :articles
end

or something like this:

class Article < ActiveRecord::Base
  has_many :articleTagList
  has_many :tags, :through => : articleTagLists
end

class Tag < ActiveRecord::Base
  has_many :articleTagList
  has_many :articles, 开发者_如何学运维:through => :articleTagLists
end

class ArticleTagList < ActiveRecord::Base
  belongs_to :article
  belongs_to :tag
end


Many-to-Many relationships in a normalized database will always need a third "look-up table."

If you denormalize you can get away with just having the tag id's in one field with a delimiter between them. But you also have to provide the logic to handle retrieval.

I'd personally just go with the normalized option.


If you don't want to store any information on the middle table (for example the name of the user who added tag X to the question Y), you can use the has_and_belongs_to_many: http://apidock.com/rails/ActiveRecord/Associations/ClassMethods/has_and_belongs_to_many

If you want to store something, you need to create the middle model, as your example. In your example, the ArticleTagList model should be called ArticlesTag and the database table should be articles_tags, by convention.

0

精彩评论

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