Tag: json

带有远程Rails服务器的BackBone客户端

背景: 我使用“rails g scaffold hotel name stars:integer”来快速启动(并在数据库中插入一些记录),并在rails app之外编写一个Backbone客户端。 我使用Safari文件在本地打开Backbone客户端:///Users/lg/Workspace/www/index.html用于测试客户端,因为我的想法是将rails服务器放在主机上(例如Heroku)并插入Backbone客户端进入PhoneGap应用程序。 我的骨干客户端只有几行: Hotel = Backbone.Model.extend({ initialize: function(){ console.log(“initialize Hotel”) } }); Hotels = Backbone.Collection.extend({ model: Hotel, url: ‘http://0.0.0.0:3000/hotels’ }); 但是当我获取带有主干的酒店时,rails会使用format.html进行响应,而不是Backbone可以解析的format.json 。 hotels_controller.rb # GET /hotels # GET /hotels.json def index @hotels = Hotel.all respond_to do |format| format.html # index.html.erb format.json { render json: @hotels } end end […]

rails – 如何在视图中呈现JSON对象

现在我正在创建一个数组并使用: render :json => @comments 这对于一个简单的JSON对象来说没什么问题,但是现在我的JSON对象需要几个帮助器,它们破坏了所有内容并且需要在控制器中包含帮助器,这似乎会导致更多问题而不是解决。 那么,我如何在视图中创建这个JSON对象,在使用帮助器时我不必担心做任何事情或破坏任何东西。 现在我在控制器中制作JSON对象的方式看起来像这样的东西? 帮我把它迁移到视图:) # Build the JSON Search Normalized Object @comments = Array.new @conversation_comments.each do |comment| @comments < comment.id, :level => comment.level, :content => html_format(comment.content), :parent_id => comment.parent_id, :user_id => comment.user_id, :created_at => comment.created_at } end render :json => @comments 谢谢!

使用Jbuilder(或其他)Rails JSON API布局

在我的rails 3.2应用程序中,我使用jbuilder来呈现来自我的JSON api的响应。 我想为所有API响应提供一个通用结构,并且布局可能是保持我的视图DRY的可能解决方案。 例如:我希望每个回复都是以下forms: { status: “ok|error|redirect”, data: { … JSON specific to the current view … }, errors: [ … ], notes: [ … ] } (其中数据的值是视图提供的json结构,其他所有内容都来自布局) 但是:我无法让jbuilder布局正确地产生视图。 # in layout json.data yield # in view json.some “value” 结果是: {“data”:”{\”some\”:\”value\”}”} # arg! my json has become a string 以另一种方式尝试: # in layout yield […]

Rails:format.js或format.json,还是两者兼而有之?

可能很明显,但我仍然缺乏基本知识。 内部控制器,既可以使用,也可以使用Javascript,所以两者都是一样的?

使用active_model_serializers序列化深层嵌套关联

我正在使用Rails 4.2.1和active_model_serializers 0.10.0.rc2 我是API的新手,并选择了active_model_serializers因为它似乎成为rails的标准(尽管我不反对使用RABL或其他序列化程序) 我遇到的问题是我似乎无法在多级关系中包含各种属性。 比如我有: 项目 class ProjectSerializer < ActiveModel::Serializer attributes :id, :name, :updated_at has_many :estimates, include_nested_associations: true end 和估计 class EstimateSerializer < ActiveModel::Serializer attributes :id, :name, :release_version, :exchange_rate, :updated_at, :project_id, :project_code_id, :tax_type_id belongs_to :project belongs_to :project_code belongs_to :tax_type has_many :proposals end 建议 class ProposalSerializer < ActiveModel::Serializer attributes :id, :name, :updated_at, :estimate_id belongs_to :estimate […]

Rails:在JSON输出中包含相关对象

我有一个属于用户的笔记类(即用户可以创建许多笔记)。 从笔记控制器剪辑 class NotesController < ApplicationController before_filter :authenticate_user! respond_to :html, :xml, :json # GET /notes # GET /notes.xml def index @notes = Note.includes(:user).order("created_at DESC") respond_with @notes end 当我在json结果中请求索引例如/notes.json时,它返回注释但只返回用户对象的user_id。 我希望它还包括user.username(并且好奇如何嵌入整个用户对象)。 奖金问题:我找不到让列显示为author_id的方法,并将其与用户联系起来。 如果这很容易做到,你怎么做?

Rails Active Model Serializer – has_many并访问父记录

我正在尝试使用Active Model Serializer构建一些Rails模型的JSON表示,其中一些模型嵌入了其他模型。 例如,我有Event和Attendees,Event has_and_belongs_to_many Attendees。 class EventSerializer < ActiveModel::Serializer attributes :name has_many :attendees, serializer: AttendeeSerializer end class AttendeeSerializer < ActiveModel::Serializer attributes :name end 这将导致JSON像{ name: ‘Event One’, attendees: [{ name: ‘Alice’ }, { name: ‘Bob’ }] } 。 现在,我想补充与会者对此次活动所说的内容。 让我们说,评论belongs_to事件,belongs_to参加者。 我想在事件的序列化输出中包含所述评论,因此它将成为{ name: ‘Event One’, attendees: [{ name: ‘Alice’, comments: [{ text: ‘Event One was […]

如何在rails 3function测试中发布JSON数据

我打算在我的项目中的请求和响应中使用JSON数据,并在测试中遇到一些问题。 搜索一段时间后,我发现以下代码使用curl发布JSON数据: curl -H “Content-Type:application/json” -H “Accept:application/json” \ -d ‘{ “foo” : “bar” }’ localhost:3000/api/new 在控制器中,我可以使用params[:foo]访问JSON数据,这非常简单。 但是对于function测试,我只找到post和xhr ( xml_http_request别名)。 如何在rails中编写function测试以达到与使用curl相同的效果? 或者我应该以其他方式进行测试? 这是我尝试过的。 我在action_controller/test_case.rb找到xhr的实现,并尝试添加jhr方法,只需更改’Conetent-Type’和’HTTP_ACCEPT’。 (在test/test_helpers.rb添加。) def json_http_request(request_method, action, parameters = nil, session = nil, flash = nil) @request.env[‘Content-Type’] = ‘Application/json’ @request.env[‘HTTP_ACCEPT’] ||= [Mime::JSON, Mime::JS, Mime::HTML, Mime::XML, ‘text/xml’, Mime::ALL].join(‘, ‘) __send__(request_method, action, parameters, session, flash).tap do @request.env.delete […]

Rails:将API请求限制为JSON格式

我想限制所有API控制器的请求被重定向到JSON路径。 我想使用重定向,因为URL也应根据响应而改变。 一种选择是使用before_filter将请求重定向到相同的操作但强制JSON格式。 这个例子还没有用! # base_controller.rb class Api::V1::BaseController < InheritedResources::Base before_filter :force_response_format respond_to :json def force_response_format redirect_to, params[:format] = :json end end 另一种选择是限制路线设置中的格式。 # routes.rb MyApp::Application.routes.draw do namespace :api, defaults: { format: ‘json’ } do namespace :v1 do resources :posts end end end 我希望所有请求最终都是JSON请求: http://localhost:3000/api/v1/posts http://localhost:3000/api/v1/posts.html http://localhost:3000/api/v1/posts.xml http://localhost:3000/api/v1/posts.json … 你会推荐哪种策略?

Backbone和Rails关联:避免JSON HashWithIndifferentAccess错误

我正试图让我的骨干协会在rails应用程序中工作,而我在尝试更新现有模型时遇到了困难。 特别是,Rails抛出以下错误: 在2012-01-04 02:36:14 +1000开始PUT“/ posts / 2”为127.0.0.1 由PostsController处理#update更新为JSON参数:{“post”=> {“content”=>“Seconderona”,“created_at”=>“2012-01-03T10:51:09Z”,“id”=> 2,“ title“=>”第二个测试post“,”updated_at“=>”2012-01-03T10:51:09Z“,”评论“=> [{}]},”id“=>”2“}后期加载( 0.2ms)SELECT“posts”。* FROM“posts”WHERE“posts”。“id”=? LIMIT 1 [[“id”,“2”]]警告:无法批量分配受保护的属性:id已完成500内部服务器错误15ms ActiveRecord :: AssociationTypeMismatch(评论(#70104367824560)预期,获得ActiveSupport :: HashWithIndifferentAccess(#70104367278120)): app / controllers / posts_controller.rb:62: block in update’ app/controllers/posts_controller.rb:61:in中的block in update’ app/controllers/posts_controller.rb:61:in block in update’ app/controllers/posts_controller.rb:61:in block in update’ app/controllers/posts_controller.rb:61:in更新中’ 一些东西: 这是在(例如)触发的: c = window.router.comments.models[0] c.save({content: ‘Changed content’}) 此外,是的,’accepts_nested_attributes_for’出现在模型中。 下面的(违规)代码几乎是从thougtbot的“rails on rails”电子书中逐字记录的,我也尝试过关注骨干关系gem的文档。 […]