George Armhold
George Armhold

Reputation: 31074

Rails: Ajax-enabled form without a model object

I'm new to Rails and having a hard time figuring out how to create a form that submits over Ajax without having a corresponding model object.

My use case is a simple form that collects an email address and sends it an email; there's nothing to be persisted, so no model.

In cases where I do have a model, I've had success with form_for(@model, remote: true). I can't seem to find the right helper for the case where there is no model. I tried form_tag(named_path, remote: true) and that works, but does not use Ajax.

Pointers to an example with an example with a proper controller, .html.erb and routes.rb would be really appreciated.

Upvotes: 0

Views: 534

Answers (1)

George Armhold
George Armhold

Reputation: 31074

Here's how I solved it. The key was using form_tag and specifying a hash with an argument that properly matched my route. For my business logic, I need to pass in an "id" param, which is used in the controller logic.

<%= form_tag(sendmail_path({ id: 1}), remote: true) do %>
  <%= text_field_tag :email, params[:email] %>
  <%= submit_tag "Send", remote:true %>
<% end %>

routes.rb:

MyApp::Application.routes.draw do
  post '/sendmail/:id(.:format)' => 'mycontroller#sendmail', :as => 'sendmail'
  # etc...
end

I also had to supply a sendemail.js.erb template which updates the form after submission.

Upvotes: 3

Related Questions