A
A
Anton Ivanov2019-02-02 03:23:40
Ruby on Rails
Anton Ivanov, 2019-02-02 03:23:40

Who should take responsibility for creating a model from a custom structure?

Hello.
There are 2 models. Let's call them Orderand OrderItem
Model instance OrderItemcan be created both in a standard way (by passing all the required model parameters), and in a non-standard way, by passing a structure with fields that differ from the model fields. With these fields, certain manipulations were carried out, the result of which is a structure with standard model fields.
Who (and how) should be responsible for creating a model from custom fields? I have three options. I ranked them from worst (in my opinion) to best.
Option 1: Standard model fields are prepared by the controller. Why is this option least liked, because a non-standard structure can be used when creating this model as a model associationOrder
Option 2: Create your own method to create the model. For example def create_from_custom_struct. I like this option a little more, but it requires some collective farm to support the new / save methods when using non-standard fields.
Option 3: attr_writer for each non-standard field. I like this option the most, I don't see any cons yet.
The question is, am I right that option 3 is the most correct? Or maybe I'm missing some fourth option?
Thank you.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
F
fairwind, 2019-02-02
@fairwind

Instead of parameters, pass an instance of the desired class that returns "standard" fields, and inside the transform fields, as needed.

class BaseItem
class ExtendedItem < BaseItem
...
OrderItem.new(BaseItem.new(params))
OrderItem.new(ExtendedItem.new(params))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question