avram
avram copied to clipboard
Handle has_many nested forms
class TaskForm < Task::BaseForm
allow title
end
class TaskListForm < TaskList::BaseForm
allow title
has_many task_forms : TaskForm
end
# Use in an action
TaskListForm.create(params) do |task_list, form|
# Handle like a normal form
end
# In a page
text_input @task_list_form.title
@task_list_form.task_forms.each do |task_form|
text_input task_form.title
end
Some ideas for implementation
I think that a good starting point would be adding many_nested
and many_nested?
to LuckyRecord::Paramable
Basically this would just be an abstract def that would need to then be implemented by LuckyRecord::Params
.
Then you'd need to go the lucky repo and implement many_nested
in Lucky::Params
. For that it should:
- Look for form params in this format:
form_name:field_name[position]
. Example:tasks:title[0]
would be the title for the first task.tasks:body[0]
would be the body for the first task. Get it withparams.many_nested(:task)
- JSON is much easier. It looks for an array under the given form name. E.g.
params.many_nested(:tasks)
gets{tasks: [{title: "title", body: "body"}]}
- It treats all JSON fields as string. So:
{users: [{age: 30}]}
would return[{"age" => "30"}]
in Crystal
Prior art
- https://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html
- https://www.pluralsight.com/guides/ruby-on-rails-nested-attributes
This one also might be really tricky, but if someone wants to give it a go I'd be grateful!
see https://github.com/luckyframework/lucky/pull/681
I'm not quite sure what the implementation of many_nested
in https://github.com/luckyframework/lucky_record/blob/topic/many_nested/src/lucky_record/params.cr should look like...
I am curious in a resolution to this
There's already a PR https://github.com/luckyframework/avram/pull/53 I think it just needs to be revisited.
Unfortunately that PR only adds the method for accessing the params, but then you'd still need a ton of logic for handling it in the operation :(
@wontruefree this will definitely be done, but it requires quite a lot of work and handling of many edge-cases. Also needs to be flexible enough that you can use it for the varying ways people might use it. 😅 I've got some ideas for how this will work, but I need to find time to just sit down and focus as it will require a lot of work
Awesome thanks for the update.
Has anyone looked more into this?
@wontruefree On the list of things to do. I just have a lot of things to do :P
Yeah, there's already that PR open for it. We just need to revisit it. Make sure it's up to date with master, and all that stuff.
Unfortunately that PR is the tip of the iceberg :( Will require lots of work on the save operation to actually implement it :(