限制 rails 控制器响应中的特定字段 [英] Restrict specific fields in the response of rails controller

查看:25
本文介绍了限制 rails 控制器响应中的特定字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像

这样的控制器动作

def 索引@videos = Video.all.to_aresponse_to do |格式|format.xml { 渲染:xml =>@视频 }format.json { 渲染:json =>@视频 }结尾结尾

视频具有nametitle 属性.

我希望返回的 xml 只包含 title.

我如何从响应中限制它.

解决方案

这样做:

def 索引@videos = Video.allresponse_to do |格式|format.xml { 渲染:xml =>@videos.to_xml( :only => [:title] ) }format.json { 渲染:json =>@videos.to_json( :only => [:title] ) }结尾结尾

您可以在序列化文档中找到更多信息.>

I have a controller action like

def index
  @videos =  Video.all.to_a

  respond_to do |format|
    format.xml  { render :xml => @videos }
    format.json { render :json => @videos }
  end
end

Video has attributes name and title.

I want the return xml to contain only title.

How do I restrict it from the response.

解决方案

Doing it like this:

def index
  @videos =  Video.all

  respond_to do |format|
    format.xml  { render :xml => @videos.to_xml( :only => [:title] ) }
    format.json { render :json => @videos.to_json( :only => [:title] ) }
  end
end

You can find more info about this at the serialization documentation.

这篇关于限制 rails 控制器响应中的特定字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆