How to create embeddable HTML form from a Rails application

笑着哭i 提交于 2019-12-06 13:32:18

问题


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


来源:https://stackoverflow.com/questions/17096055/how-to-create-embeddable-html-form-from-a-rails-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!