Reputation: 1783
I am building a form that interacts with third party API via JSON. My goal is to be able to both create a JSON call based on the values input into the form. If the JSON response returns an error, I would like to have the form_fields maintain the values used to generate the response.
How should I go about building the form and binding the JSON fields to the form?
When tied to a model i'd usually have something like:
<%= form_for @person do |f| %>
<%= text_field_with_label f, :first_name %>
<% end %>
and in my controller i'd have:
def new
@person = Person.new
end
But how would I set this up when there is no model. What would be in the new action on the controller? An empty JSON structure? How would I setup the input fields so they keep the values used to make the initial JSON call (in the case where the response takes the user back to the form when there is an error).
Upvotes: 1
Views: 1315
Reputation: 1144
Instead of using using form_for you'd be using form_tag and other *_tag methods. Your example above would be:
<%= form_tag :controller => 'users', :action => 'myaction' %>
First Name <%= text_field_tag :name, params[:name] %>
<% end %>
Which you could then handle in the controller and action of your choice. Remember you'll need to add a custom route for your action in the routes.rb file too:
get 'users/new'
post 'users/myaction'
The general logic for the controller action would be:
def new
end
def myaction
success = call_external_service_here
if success
redirect_to 'somewhere'
else
render 'new'
end
You would leave the new method blank in the controller. The second argument to the text_field_tag provides the value for the field, which in the new action will be blank, but the value will be inserted when the form page is rendered if the external service call results in failure.
Upvotes: 1