开发者

Creating a model within a model in Rails

Is it possible to create a model object f开发者_运维问答rom within another model form?

Let's say I have an Article model and a Term model who have a has_and_belongs_to_many relationship through a join table. (Terms are almost like tags, but have a definition column.)

I want the user to be able to add terms to the article when editing it (probably using check boxes), but I also the user to be able to create a new term if he can't find it in the list. How can this be done? I want the user to be able to create a term with a definition inside the article edit form. Is this possible?


Read into "nested objects" or "nested attributes". This might be a good starting point: http://ryandaigle.com/articles/2009/2/1/what-s-new-in-edge-rails-nested-attributes


You could always separate the fields inside the params hash (hashes with different keys, likely :term => {} and :article => {}) that is passed back to the controller and then handle it separately once you are in the controller.


Ryan on railscasts shows how to do something similar in these two screencasts. He adds questions and answers to a survey website.

Nested Model Form 1

Nested Model Form 2

Along with that this resource on nested attributes will help you piece it all together.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜