cbm*_*eks 1 jquery ruby-on-rails
没有一个教程我似乎做了我想要做的事情.很简单,我希望用户能够向控制器提交POST请求("喜欢"视频)并让控制器使用JSON对象进行响应.任何帮助,将不胜感激.
谢谢
编辑因为SO正在弄乱格式化,这里也是我的代码的要点:https: //gist.github.com/813503
class LikesController < ApplicationController
before_filter :get_ids
respond_to :json, :js
def videolink
results = {}
# check to see if the user has liked this videolink before
if current_user
liked = Like.video?(current_user, @vid_id)
results["status"] = "OK"
results["liked"] = liked
else
results["status"] = "Error"
results["message"] = "User not logged in"
end
respond_with( results.to_json )
end
def update
results = {}
if current_user
results["status"] = "OK"
else
results["status"] = "Error"
results["message"] = "User not logged in"
end
respond_with( results.to_json )
end
private
def get_ids
@vid_id = params[:videolink_id]
end
end
Run Code Online (Sandbox Code Playgroud)
$("#likeVideo").click(function() {
$.ajax({
contentType: "application/json",
data: { game_id: game_id, videolink_id: current_video["videolink"]["id"] },
dataType: "json",
type: "POST",
url: "/likes/" + game_id,
success: function(data) {
console.log("Success", data);
}
});
return false;
});
Run Code Online (Sandbox Code Playgroud)
resources :likes do
collection do
get "videolink"
end
member do
post :update
end
end
Run Code Online (Sandbox Code Playgroud)
undefined method `{"status":"OK"}_url' for #<LikesController:0x0000010178be58>
undefined method `{"status":"OK"}_url' for #<LikesController:0x0000010178be58>
如果要发回自定义JSON,而不是respond_with(results.to_json)...只是渲染文本
render :text=>results.to_json
Run Code Online (Sandbox Code Playgroud)
responds_with是一种让您轻松发回物品及其位置(url)的方法.这就是为什么你的错误告诉你"_url"无效的原因.
有关responds_with的更多信息,请参阅http://ryandaigle.com/articles/2009/8/10/what-s-new-in-edge-rails-default-restful-rendering
如果请求了另一种格式,(即:xml或:json)
- 如果是GET请求,则在资源上调用:to_format方法并将其发回
- 如果资源有验证错误,请使用:unprocessable_entity状态代码以请求的格式发回错误
- 如果是POST请求,则在资源上调用:to_format方法,然后将其发送回:created status和新创建的资源的:location
- 否则,发回:ok响应,没有身体