2013-10-14 201 views
0

我產生命名空間中的模型,我怎麼可以設置很多一對多
關係,類別有很多帖子,帖子有很多類許多一對多的模型關係

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 

回答

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

嘗試將關聯添加到CategoryPosts到Category和Post模型中。例如:

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

我相信你需要爲Category和Post模型做這件事。