Ruby on Rails中的自定义格式 [英] Custom formats in Ruby on Rails

查看:122
本文介绍了Ruby on Rails中的自定义格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Ruby on Rails中创建一个网站,用户可以使用RESTful Authentication进行登录。有人可以得到一个特定的用户使用HTML,XML和JSON,就像脚手架。但是我想添加一个格式:vCard(例如/users/1.vcard)。这有一个特定的格式,但我如何定义我自己的格式?使用视图,还是必须使用另一种方式?感谢您在 /config/initializers/mime_types.rb 文件中添加一个新的注册,以供您在 /config/initializers/mime_types.rb 你的格式。它应该看起来像这样:
$ b $ pre $ m $ c $ mime :: Type.registertext / x-vcard,:vcard #The: vcard是重要的部分

之后(你将不得不重新启动你的应用程序来获取更改),你可以像其他任何格式一样响应这个符号:

pre code然后在你的控制器动作
def show
respond_to do | format |
format.html#render html
format.vcard {#render vcard}
end
end

从评论中加入(感谢nanda): b
$ b

在你的views文件夹中,将vCard模板放入show.vcard.erb文件(例如)。


I'm creating a website in Ruby on Rails, where users can login using RESTful Authentication. Someone can get a specific user using html, xml and json, just like scaffolding. But I want to add one more format: vCard (e.g. /users/1.vcard). This has a specific format, but how do I define my own formats? Using views, or must I use another way? Thanks

解决方案

In your /config/initializers/mime_types.rb file, add a new registration for your format. It should look something like this:

Mime::Type.register "text/x-vcard", :vcard  #The :vcard is the important part

After that (you'll have to restart your app to pick up the change), you can respond to the symbol like any other format:

# then in your controller action
def show
  respond_to do |format|
    format.html # render html
    format.vcard { #render vcard }
  end
end

Adding from comments (thanks nanda):

In your views folder, then, you would put the vCard template into a show.vcard.erb file (for example).

这篇关于Ruby on Rails中的自定义格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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