【发布时间】:2014-01-23 16:28:54
【问题描述】:
我正在尝试让我的 google chrome 扩展使用 Ajax 将数据发送到我的 ruby on rails 网站,但我无法弄清楚这里发生了什么:
我看到我的 Rails 服务器已收到我要发送的数据(两个数组),但有 404?然后我有一个关于用户 ID 的错误?
Started POST "/add_service" for 127.0.0.1 at 2014-01-24 00:34:37 +0800
Processing by UsersController#add_service as HTML
Parameters: {"urlArray2"=>["0.0.0.0", "item.jd.com", "stackoverflow.com", "www.google.com.hk"], "countArray2"=>["3670", "20", "2", "2"]}
User Load (11.4ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT 1 [["id", 1]]
Completed 404 Not Found in 13ms
ActiveRecord::RecordNotFound - Couldn't find User without an ID:
...
...
这是我的 Chrome 扩展中的 Ajax:
jQuery.ajax({
type: "POST",
dataType: "JSON",
url: "http://0.0.0.0:3000/add_service",
data: ({'urlArray2':urlArray2,'countArray2':countArray2}),
success: function(){
//alert("Web services loaded into ConsultFred.");
}
});
这是我的用户控制器:
skip_before_filter :verify_authenticity_token, :only => [:add_service]
...
...
def add_service
logger.debug "This is working..."
#@user = current_user
#@user.sitearray = params[:urlArray2]
repsond_to do |format|
format.html { redirect_to root_url }
format.json { redirect_to root_url }
end
end
我的 routes.rb(编辑:添加更多信息):
resources :users, :only => [:index, :show, :edit, :update ] do
post :share_to_linkedin, on: :member
end
post 'add_service', to: 'users#add_service'
[编辑 1 月 24 日]
现在看AJAX响应,其实是参数有问题,没有提供user.id号:
ActiveRecord::RecordNotFound at /add_service
============================================
> Couldn't find User without an ID
我怎么可能发送它呢? ajax 请求是 chrome 扩展的外部请求?
【问题讨论】:
-
你在哪里设置 current_user 变量?因为如果你试图从外部访问 current_user 变量可能没有设置。
-
current_user 是 ApplicationController 中的辅助方法。我认为我现在遇到的问题是方法 logger.debug "This is working..." 的第一行甚至没有被执行?
-
@MarkoJurinčič 你是对的!我将如何解决这个问题? chrome 扩展(来自外部)不够了解...
-
您可以在 post 参数中添加一个额外的参数 user_id,然后只需 user = User.find(params[:user_id])...另外我正在使用 Advance Rest 客户端来测试休息通信(发布参数)
-
@MarkoJurinčič 问题是 ajax 发布请求来自 chrome 扩展,并且它不知道 user_id。也许我的 chrome 扩展需要登录到我的 rails 站点才能获取 user_id?如果是这样,有什么好的方法吗?
标签: ruby-on-rails ajax google-chrome-extension