模型的多对多关系

时间:2013-10-14 10:15:39

标签: ruby-on-rails activerecord

我生成了命名空间模型,如何设置多对多的模型 关系,类别有很多帖子,帖子有很多类别

rails g model Blog::Post body:text, title:string
rails g model Blog::Category title:string
rails g model Blog::CategoryPost post_id:integer, category_id:integer

我的模型看起来像

class Blog::Category < ActiveRecord::Base
  attr_accessible :title
  has_many :posts, :class_name => 'Blog::Post', :through => :blog_categories_posts
end
class Blog::CategoryPost < ActiveRecord::Base
  belongs_to :category, :class_name => 'Blog::Category'
  belongs_to :post, :class_name => 'Blog::Post'
end
class Blog::Post < ActiveRecord::Base
  attr_accessible :body, :title
  has_many :categories, :class_name => 'Blog::Category', :through => :blog_categories_posts
end

2 个答案:

答案 0 :(得分:1)

这应该有效。您需要指定与中间表的关系。

class Blog::Category < ActiveRecord::Base
  attr_accessible :title
  has_many :categories_posts, :class_name => 'Blog::CategoryPost'
  has_many :posts, :class_name => 'Blog::Post', :through => :categories_posts
end
class Blog::CategoryPost < ActiveRecord::Base
  belongs_to :category, :class_name => 'Blog::Category'
  belongs_to :post, :class_name => 'Blog::Post'
end
class Blog::Post < ActiveRecord::Base
  attr_accessible :body, :title
  has_many :categories_posts, :class_name => 'Blog::CategoryPost'
  has_many :categories, :class_name => 'Blog::Category', :through => :categories_posts
end

答案 1 :(得分:1)

尝试将CategoryPosts的关联添加到Category和Post模型。例如:

class Blog::Category < ActiveRecord::Base
  ...
  has_many :blog_category_posts, :class_name => "Blog::CategoryPost"
  ...
end

我认为您需要为Category和Post模型执行此操作。

相关问题