A
A
Axel_F2017-01-04 21:12:52
Ruby on Rails
Axel_F, 2017-01-04 21:12:52

How to process such a form?

There is a `Training` model and an `Exercise` model. There is a one-to-many relationship between them. There is also a `Group` model, it is needed in order to highlight the necessary exercises in a group, which can be given a name. That is, `Exercise` simultaneously belongs to two other models in a one-to-many relationship to each.
The result is a form where there is a list of exercises, and each exercise can have a group name.
It turned out to make the form itself, but it does not work out normally to process it in the controller. The problem is that when creating a new exercise, it needs to give out the id of an already created group. But if a new workout is recorded immediately, and new exercises are already attached to it, then in order to assign a group, you must first create it, get the id of the created record, and only then you can create the exercise itself.
Without a group model, it would be possible to do with standard tools (and fit in a couple of lines), since all records are created sequentially, and so you have to write the whole process manually. And if for the create method the code turned out to be even more or less understandable, then when editing (update) it turns out to be a complete mess.
The question is the following. Is there a more elegant solution for this situation than to prescribe everything manually or not? Or maybe there is an option to slightly change the architecture to avoid such crutches.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Z
ZloyHobbit, 2017-01-12
@Axel_F

There is some confusing explanation. Please provide a code example.
From what I understand, when you create an object of one model, you want to create an object of another, which is not connected with the first in any way. It is architecturally not too convenient and not too trivial. It would be better to try to somehow transform the architecture.
To use the same method when creating and updating, you can do this:
To create a model object immediately with related models, it is useful to use nested attributes.
In your case it will be something like:

class Trainig < ActiveRecord::Base
  has_many :exercises
  accepts_nested_attributes_for :exercises
end
...
training = Training.create(training_params.merge(exercises_atrributes: array_with_hashes_of_exercises_atrributes))

Moreover, in the array of parameters for exercises, you can enter data to create groups and create a group if it is absent before creating an exercise using find_or_initialize_by.
PS. As correctly said in the comments, in order to pass nested attributes from the general form, it is convenient to use fields_for.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question