开发者

Why is AJAX in Rails 3 so hard? Or, what am I doing wrong?

None of the tutorials I seem do what I'm trying to do. Very simply, I want a user to be able to submit a POST request to a controller (to "LIKE" a video) and have the controller respond back with a JSON object. Any help would be appreciated.

Thanks

EDIT Because SO is messing the formatting up, here is a gist of my code too: https://gist.github.com/813503

Here is my controller:

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

Here is my JS file:

$("#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;
});

My routes:

  resources :likes do
    collection do
      get "videolink"
    end

    member do
      post :update
    end
  end

And here is the error I get:

NoMethodError in LikesController#update

undefined method `{"status":"OK"}_url' for #<LikesController:0x0000010178be58>


If you want to send back custom JSON, Instead of respond_with(results.to_json)... just render the text

render :text=>results.to_json

The responds_with is a way for you to easily send back objects, with their location (url). So that's why your error is telling you that that '_url' is invalid.

More info on responds_with, courtesy of http://ryandaigle.com/articles/2009/8/10/what-s-new-in-edge-rails-default-restful-rendering

If another format was requested, (i.e. :xml or :json)

  • If it was a GET request, invoke the :to_format method on the resource and send that back
  • If the resource has validation errors, send back the errors in the requested format with the :unprocessable_entity status code
  • If it was a POST request, invoke the :to_format method on the resource and send that back with the :created status and the :location of the new created resource
  • Else, send back the :ok response with no body
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜