Ruby on rails 如何定义Rails 4中链接的默认格式?
我已经看到一些类似的问题: 但任何解决方案在rails 4中对我都不起作用: 在路由器中.rbRuby on rails 如何定义Rails 4中链接的默认格式?,ruby-on-rails,ruby-on-rails-4,Ruby On Rails,Ruby On Rails 4,我已经看到一些类似的问题: 但任何解决方案在rails 4中对我都不起作用: 在路由器中.rb :defaults => { :format => 'html' } before_filter :set_format def set_format request.format = 'html' end config.default_url_options = { :format => "html" } 在app/controllers/some_contro
:defaults => { :format => 'html' }
before_filter :set_format
def set_format
request.format = 'html'
end
config.default_url_options = { :format => "html" }
在app/controllers/some_controller.rb中
:defaults => { :format => 'html' }
before_filter :set_format
def set_format
request.format = 'html'
end
config.default_url_options = { :format => "html" }
在config/application.rb中
:defaults => { :format => 'html' }
before_filter :set_format
def set_format
request.format = 'html'
end
config.default_url_options = { :format => "html" }
任何人都可以。我试过所有的方法,但每次都是分开的
这是我的代码:
link_to("Read more", article_path(article, :format => "html"))
# => <a href="/1.html">Read more</a>
我想要的是:
link_to("Read more", article_path(article))
# => <a href="/1.html">Read more</a>
链接到(“阅读更多”,文章路径(文章))
# =>
请分享您的建议。如果您使用将这些选项添加到路线中,我想您最终会得到您想要的路径中的.html
。您甚至不需要修改对文章路径的调用
format: true, defaults: { format: 'html' }
我遇到了类似的事情。透过栏杆,我找到了答案
我有一个操作,我想将其默认为CSV格式,但我还想生成包含.CSV
的URL。通过这种方式,客户端只需查看URL,就可以知道它是CSV。如果没有.csv
,链接将是什么并不十分清楚
我的路线是这样的:
get 'customers/with_favorite_color/:color' => 'customers#with_favorite_color', as: :customers_with_favorite_color, format: 'csv'
customers_with_favorite_color_url(color: 'blue', format: :csv)
# => `http://localhost:3000/customers/with_favorite_color/blue
我是这样生成链接的:
get 'customers/with_favorite_color/:color' => 'customers#with_favorite_color', as: :customers_with_favorite_color, format: 'csv'
customers_with_favorite_color_url(color: 'blue', format: :csv)
# => `http://localhost:3000/customers/with_favorite_color/blue
除了,我想要http://localhost:3000/customers/with_favorite_color/blue.csv
如果路由中也指定了该格式,则该格式似乎不会添加到URL中
为了让它发挥作用,我把路线改为
get 'customers/with_favorite_color/:color' => 'customers#with_favorite_color', as: :customers_with_favorite_color, format: true, defaults: { format: 'csv' }
注意,添加/更改的选项是:format:true,默认值:{format:'csv'}
现在,当我生成URL时,我得到了我想要的.csv
customers_with_favorite_color_url(color: 'blue')
# => `http://localhost:3000/customers/with_favorite_color/blue.csv
更新
要将此应用于许多路由,可以遵循的建议并使用具有这些默认值的作用域
scope format: true, defaults: { format: 'html' } do
# Define your resources here like normal
end
我看到默认的formal是xml
,您需要将其重写为html
,所以为什么每次都不想编写:format=>“html”
?为什么要强制将请求格式转换为xml?@mohamed yakot,谢谢,正确的问题。这是一个复制粘贴mistake@michal-辛德尔,也谢谢你。谢谢你的回答。我会把它标记为正确的。只有一个问题:您是否找到全局定义它的方法(format:true,默认值:{format:'html'}
)?我的意思是,对于整个项目?我相信你可以按照这里的建议对其进行全局定义:我用这些附加信息更新了我的答案。