How to create embeddable HTML form from a Rails ap

2019-06-06 13:04发布

问题:

I want to create an embeddable HTML <form> that POSTs to a rails controller. This form would be embedded on a non-rails site.

What approach have you taken to create a form like this? Should I use an <iframe>, or JS? Or something completely different?

As a secondary part to this question, I'd also need this form to be able to "bubble up" events into the parent page that it is embedded into, such that I could capture all of the fields of the form to make calls to external APIs like Google Events or Marketo.

回答1:

You can just include normal HTML form which has its action set to the route you need.

This form will create an employee with the given name:

<form action="http://example.com/employees?return_url=...some_url..." 
      method='post'>
    <input name="employee[name]" type=text/>
    <input type=submit value='create'/>
</form>

Be sure, in your controller to redirect back to your non rails site. When your action is also used in the rails site itself, you'll need some way to indicate where your action should redirect to.

def create
   employee = Employee.create(params[:employee])
   if params[:return_url]
      redirect_to params[:return_url]
   else
      redirect_to employee_path(employee)
   end   
end

Be also sure to disable forgery_protection for that action.

class EmployeesController < ApplicationController
    skip_before_filter :verify_authenticity_token, :only => [:create]
    # actions
end