How to create a form for a reference_many association with existing references? (mongoid 2.0.0.beta.20)
Assume I've a model A which is referencing many other models B. I have 开发者_开发百科a set of B's and want to create a form which creates/destroys the association (many-to-many).
What's is the best approach to do that? Can I somehow use accept_nested_attribures_for
and the fields_for
helper like I'd use to create new reference objects?
Edit: Example
I have a model Category and another model Post. I want each Post to reference_many Categories. I have a static set categories. So I don't want to create new categories but create references to the existing categories.
What is the easiest way to extend the new/edit form of Post with a category selection. Right now I'm processing the categories manually because I couldn't figure out how to use accept_nested_attribures_for
and fields_for
with existing reference objects.
You can use references_and_referenced_in_many
for describing associations between Posts and Categories but it exists in mongoid since 2.0.0.rc.1. You can explicitly define model for many-to-many associations, in your case, for ex., 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
In the view (I use simple_form and haml here, but the same approach with old dirty form_for and 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
The last (but not least) thing is setup_post
helper which did the trick:
module PostsHelper
def setup_post(post)
post.tap do |p|
p.post_categories.build if p.post_categories.empty?
end
end
end
That's all.
精彩评论