Rails:带有 erb 的动态 robots.txt [英] Rails: dynamic robots.txt with erb

查看:39
本文介绍了Rails:带有 erb 的动态 robots.txt的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在我的 Rails (3.0.10) 应用程序中呈现动态文本文件 (robots.txt),但它继续将其呈现为 HTML(控制台说).

I'm trying to render a dynamic text file (robots.txt) in my Rails (3.0.10) app, but it continues to render it as HTML (says the console).

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

app/views/sites/robots.txt.erb:

app/views/sites/robots.txt.erb:

Sitemap: <%= @site.url %>/sitemap.xml

但是当我访问 http://www.example.com/robots.txt 时,我得到一个空白页面/源,并且日志显示:

But when I visit http://www.example.com/robots.txt I get a blank page/source, and the log says:

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 类型是什么:

Note: I added this to config/initializers/mime_types, cause Rails was complaining about not knowing what the .txt mime type was:

Mime::Type.register_alias "text/plain", :txt

注意 2:我确实从公共目录中删除了库存 robots.txt.

Note 2: I did remove the stock robots.txt from the public directory.

推荐答案

我认为问题是如果你在控制器中定义了 respond_to,你必须使用 respond_with在行动中:

I think the problem is that if you define respond_to in your controller, you have to use respond_with in the action:

def robots
  @site = Site.find_by_subdomain # blah blah
  respond_with @site
end

另外,尝试明确指定要渲染的 .erb 文件:

Also, try explicitly specifying the .erb file to be rendered:

def robots
  @site = Site.find_by_subdomain # blah blah
  render 'sites/robots.txt.erb'
  respond_with @site
end

这篇关于Rails:带有 erb 的动态 robots.txt的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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