Aydar Omurbekov
Aydar Omurbekov

Reputation: 2127

Many-to-many relationships for models

I generated namespaced models and how can i set many-to-many
relationships, category has many posts, post has many categories

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

and my models looks like

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

Upvotes: 0

Views: 72

Answers (2)

joncalhoun
joncalhoun

Reputation: 1518

Try adding the associations to the CategoryPosts to the Category and Post models. eg:

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

I believe you need to do this for both the Category and the Post models.

Upvotes: 1

Edgars Jekabsons
Edgars Jekabsons

Reputation: 2853

This should work. You need to specify relation to intermediate table.

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

Upvotes: 1

Related Questions