我进行了一个AJAX调用,将一个javascript变量发送给我的控制器中的一个方法。我的控制器是这样的:
def registration
@fund = params[:funds]
@index = params[:indexDecision]
render json: 'ok'
end
def create
@user = User.new(ticket_params)
respond_to do |format|
if @user.save
format.html { redirect_to @user, notice: 'User was successfully created.' }
format.json { render :show, status: :created, location: @user }
Record.create(fund: @funds, weight: @weight)
else
format.html { render :new }
format.json { render json: @user.errors, status: :unprocessable_entity }
end
format.js
end
end
这是我的AJAX调用:
$.ajax({
url: "/record",
type: "POST",
data: {
funds: funds,
indexDecision: indexDecision
},
complete: function(){
console.log('Congrats');
}
});
这是我的配置路由文件:
resources :users
post '/record' => 'users#registration'
我的AJAX调用工作良好。但是现在我需要实例变量@fund
和@index
在create方法中可用。我读到我必须使用私有方法,以便私有方法中的实例变量可以在其他方法中使用。
我试过了,但我有一个error 400 bad request
。
如何使@funds和@index变量在create方法中可用?
您的代码应该看起来像这样(为了简单起见,我忽略了HTML格式):
def registration
user = User.new(ticket_params)
if user.save
fund = params[:funds]
index = params[:indexDecision]
Record.create(fund: funds, weight: weight)
render json: 'ok'
else
# report error here
end
end