javascript - Rails + simple_form + remote_true + custom controller: how to handle different form actions for 'new' and 'edit'? -
i'm following tutorial: http://www.gotealeaf.com/blog/the-detailed-guide-on-how-ajax-works-with-ruby-on-rails variation: after creating scaffold 'tasks' (controller, model, views...) i've created new controller, named 'demo', test ajax way. 'demo' controller has following actions: index, new_task, create_task, edit_task, update_task. routes adjusted.
when render form (app/views/demo/_form.html.erb)
<%= simple_form_for @task, remote: true |f| %> <%= f.input :description %> <%= f.input :deadline %> <%= f.button :submit %> <% end %>
the form 'action' '/tasks', corresponds 'controller:tasks, action:create', controller "old html" way, while ajax stuff in 'demo' controller.
so, following answers found on web i've added 'url' parameter:
<%= simple_form_for @task, remote: true, url: '/demo/create_task' |f| %> <%= f.input :description %> <%= f.input :deadline %> <%= f.button :submit %> <% end %>
in case works 'new/create' actions. when it's time update model should use '/demo/update_task' path. rails way handle this?
add line before form: <% url = @task.new_record? ? "/demo/create_task" : "/demo/update_task?id=#{@task.id}" %>
have 2 different forms, 1 creating, other editing, 'new_task.js.erb' point '_form_for_creating.html.erb' , 'edit_task.js.erb' point other one. not dry actually.
even more ugly:: have 'tasks' controller redirect 'update_task' in 'demo' controller. wouldn't rely on because tasks controller supposed deleted after testing.
i chose add line before form:
<% url = @task.new_record? ? "/demo/create_task" : "/demo/update_task?id=#{@task.id}" %> <%= simple_form_for @task, remote: true, url: url |f| %> <%= f.input :description %> <%= f.input :deadline %> <%= f.button :submit %> <% end %>
i feel it's not perfect works.
of course there few things adjust:
- add route
patch 'demo/update_task'
update_task
in demo controller should load tasks after updating attributes
Comments
Post a Comment