【问题标题】:js response with association带有关联的 js 响应
【发布时间】:2012-11-20 08:52:28
【问题描述】:

我正在执行跨域 ajax 调用以从我的 rails 应用程序中获取一些数据。为此,我使用了一种我发现的很棒的方法,它就像一个魅力。然而,Rails 并没有呈现与它相关的关联。因为我确实想要这些信息,所以我尝试更改我的 format.js,但在格式化正确的输出时失败了。

这就是我现在的旅行展示方法(效果很好):

respond_to do |format|
  format.html # show.html.erb
  format.js { render_json @trip.to_json }  
end

但我也想渲染@trip.triplocations。但我不知道怎么做。有谁知道这个吗?

以防万一,这是我发现的很棒的方法:

def render_json(json, options={})
  callback, variable = params[:callback], params[:variable]
  response = begin
    if callback && variable
      "var #{variable} = #{json};\n#{callback}(#{variable});"
    elsif variable
      "var #{variable} = #{json};"
    elsif callback
      "#{callback}(#{json});"
    else
      json
    end
  end
  render({:content_type => :js, :text => response}.merge(options))
end

(道具转至:http://www.sitepoint.com/json-p-output-with-rails/

提前致谢!

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 json associations


    【解决方案1】:

    (顺便说一句:你真的需要这个 render_json 方法吗?)

    format.js {render :json=> @trip.as_json(:include => :triplocations)}
    

    :include 方法将包含关联。也适用于更高的水平。 http://api.rubyonrails.org/classes/ActiveModel/Serializers/JSON.html#method-i-as_json

    【讨论】:

    • 显然对于跨域访问(jsonp)你做。阅读给出的链接并感谢您的回答!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-06
    • 2012-11-28
    • 2012-04-04
    • 1970-01-01
    • 1970-01-01
    • 2015-11-20
    • 2015-04-03
    相关资源
    最近更新 更多