Вы можете использовать references_and_referenced_in_many
для описания связей между сообщениями и категориями, но он существует в mongoid начиная с 2.0.0.rc.1.Вы можете явно определить модель для ассоциаций «многие ко многим», в вашем случае, например, PostCategory
:
class PostCategory
include Mongoid::Document
referenced_in :category, :inverse_of => :post_categories
referenced_in :post, :inverse_of => :post_categories
end
class Category
include Mongoid::Document
references_many :post_categories
end
class Post
include Mongoid::Document
references_many :post_categories, :dependent => :delete
accepts_nested_attributes_for :post_categories
attr_accessible :post_categories_attributes
end
В представлении (я использую simple_form и хамл здесь, но тот же подход со старыми грязными form_for и ERB):
= simple_form_for setup_post(@post) do |f|
...
= f.simple_field_for :post_categories do |n|
= n.input :category, :as => :select, :collection => Category.asc(:name).all
Последняя (но не менее важная) вещь - setup_post
помощник, который добился цели:
module PostsHelper
def setup_post(post)
post.tap do |p|
p.post_categories.build if p.post_categories.empty?
end
end
end
Этовсе.