我试图在我的Rails(3.0.10)应用程序中呈现一个动态文本文件(robots.txt),但它继续呈现为
HTML(控制台).
match 'robots.txt' => 'sites#robots'
控制器:
class SitesController < ApplicationController respond_to :html,:js,:xml,:css,:txt def robots @site = Site.find_by_subdomain # blah blah end end
应用程序/视图/网站/ robots.txt.erb:
Sitemap: <%= @site.url %>/sitemap.xml
但是当我访问http://www.example.com/robots.txt时,我得到一个空白页面/源代码,日志说:
Started GET "/robots.txt" for 127.0.0.1 at 2011-11-21 11:22:13 -0500 Processing by SitesController#robots as HTML Site Load (0.4ms) SELECT `sites`.* FROM `sites` WHERE (`sites`.`subdomain` = 'blah') ORDER BY created_at DESC LIMIT 1 Completed 406 Not Acceptable in 828ms
任何想法我在做错什么?
注意:我添加到config / initializers / mime_types,因为Rails抱怨不知道.txt mime类型是什么:
Mime::Type.register_alias "text/plain",:txt
注2:我从公共目录中删除了库存robots.txt.
解决方法
我认为问题是如果您在控制器中定义respond_to,则必须在操作中使用respond_with:
def robots @site = Site.find_by_subdomain # blah blah respond_with @site end
另外,尝试显式指定要渲染的.erb文件:
def robots @site = Site.find_by_subdomain # blah blah render 'sites/robots.txt.erb' respond_with @site end