如何创建与现有引用关联的reference_many 表单? (mongoid 2.0.0.beta.20)
假设我有一个模型 A,它引用了许多其他模型 B。我有一组 B,并且想要创建一个用于创建/销毁关联(多对多)的表单。
做到这一点的最佳方法是什么?我可以以某种方式使用 accept_nested_attribures_for
和 fields_for
帮助器,就像我用来创建新的引用对象一样吗?
编辑:示例
我有一个模型类别和另一个模型帖子。我希望每个帖子都reference_many类别。我有一个静态集类别。所以我不想创建新类别,而是创建对现有类别的引用。
通过类别选择扩展Post的新/编辑表单的最简单方法是什么。现在,我正在手动处理类别,因为我无法弄清楚如何将 accept_nested_attribures_for
和 fields_for
与现有参考对象一起使用。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用
references_and_referenced_in_many
来描述帖子和类别之间的关联,但它从 2.0.0.rc.1 开始就存在于 mongoid 中。您可以在您的情况下显式定义多对多关联的模型,例如PostCategory
:在视图中(我使用 simple_form 和 haml 这里,但与旧的脏 form_for 和 ERB 的方法相同):
最后(但并非最不重要的)一件事是
setup_post
帮助程序窍门:仅此而已。
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
:In the view (I use simple_form and haml here, but the same approach with old dirty form_for and ERB):
The last (but not least) thing is
setup_post
helper which did the trick:That's all.