我正在使用Rails 4.1.1 我想知道,如何在jQuery(.js.erb)中调用'create'动作? 请参阅下面我的jquery代码和我的 user_controller.rb ,我想在jquery if else 代码中调用 user_controller.rb 创建操作
的routes.rb
Rails.application.routes.draw do
resources :user
root 'user#index'
end
user_controller.rb
class UserController < ApplicationController
def index
@users = User.all
@user = User.new
end
def create
@user = User.new(user_params)
@user.save
redirect_to "/"
end
private
def user_params
params.require(:user).permit(:email)
end
end
subscribe.js.erb
$(function () {
$("#subscribe").submit(function (event) {
var input = $('.my-subscribe-message');
if(!input.is(':empty')) {
$('.my-subscribe-message').stop(true);
}
event.preventDefault();
event.stopImmediatePropagation();
var email = $("input#subscribe-email").val();
if (email == "") {
$(".my-subscribe-message").stop(true).html('<i class="fa fa-warning"></i> You must enter a valid e-mail address.');
$("input#subscribe-email").focus();
}
else if (!isValidEmailAddress( email )) {
$(".my-subscribe-message").stop(true).html('<i class="fa fa-warning"></i> E-mail address is not valid.');
$("input#subscribe-email").focus();
}
else {
$.ajax({
/* I would like to call the create action here */
success: function () {
$(".my-subscribe-message").html('<i class="fa fa-check"></i> We will be in touch soon!');
$('input#subscribe-email').val('');
}
});
}
});
});
答案 0 :(得分:4)
给这个平底船:
$.ajax({
type: "POST",
url: "/users",
data: { user: { email: "blah@blah.com" } },
});