我正在尝试在Rails中执行跨平台请求。
我的jQuery代码如下:
我的控制如下:-
def new @batch = Batch.new respond_to do |format| format.json format.html end end def create @batch = Batch.new(batch_param) respond_to do |format| if @batch.save format.json { render json: @batch, status: :created, location: @batch } format.html { redirect_to @batch, notice: "Save process completed!" } else format.html { flash.now[:notice]="Save proccess coudn't be completed!" render json: @batch.errors, status: :unprocessable_entity } format.json { render json: @batch.errors, status: :unprocessable_entity} end end end def batch_param params.require(:batch).permit(:name, :course_id, :start_date, :end_date, :status) end
但是每次我尝试使用表单添加记录时,它都会在rails日志中显示以下错误:-
我提交我的第一个数据时出错
Started OPTIONS "/batches" for 127.0.0.1 at 2017-01-11 22:02:49 +0545 ActiveRecord::SchemaMigration Load (0.5ms) SELECT "schema_migrations".* FROM "schema_migrations" ActionController::RoutingError (No route matches [OPTIONS] "/batches"):
当我一次提交数据时出错:-
Started OPTIONS "/batches" for 127.0.0.1 at 2017-01-11 22:08:50 +0545 ActionController::RoutingError (No route matches [OPTIONS] "/batches"):
谁能帮助我解决这个问题。
您需要配置Rails以支持CORS。
一种解决方案是使用rack-cors gem。
需要将以下片段添加到config / application.rb
module YourApp class Application < Rails::Application # ... # Rails 3/4 config.middleware.insert_before 0, "Rack::Cors" do allow do origins '*' resource '*', :headers => :any, :methods => [:get, :post, :options] end end # Rails 5 config.middleware.insert_before 0, Rack::Cors do allow do origins '*' resource '*', :headers => :any, :methods => [:get, :post, :options] end end end end