Creating a model in a model in Rails

Is it possible to create a model object from another model?

Say I have an Article model and a Term model that has a has_and_belongs_to_many relationship through a join table. (The 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 (possibly using checkboxes), but I am also the user to be able to create a new term if he cannot 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 editing form. Is it possible?

+2
source share
3 answers

Reading in "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

+1
source

You can always separate the fields inside the params hash (hashes with different keys, most likely: term => {} and: article => {}), which are passed back to the controller and then process it separately as soon as you are the controller.

0
source

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

Nested Model 1

Nested Model 2

Along with this, this resource nested attributes will help you put everything together.

0
source

Source: https://habr.com/ru/post/1381074/


All Articles