【发布时间】:2011-08-30 05:03:03
【问题描述】:
我想要以下目录结构:
views/
app1/
users/_user.html.erb
users/index.html.erb
app2/
users/index.html.erb
shared/
users/_user.html.erb
users/index.html.erb
在我看来,我会打电话
# app1/users/index.html
<%= render :partial => "user" %>
# => /app1/users/_user.html.erb
# app2/users/index.html
<%= render :partial => "user" %>
# => /shared/users/_user.html.erb
所以基本上,我如何告诉 Rails 在它引发缺少模板错误之前先检查 /app2/users 目录然后是共享目录?
更新
我解决了这个问题(根据 Senthil 的建议,使用 File.exist?
这是我的解决方案 - 欢迎提供反馈和建议
# application_helper.rb
# Checks for a partial in views/[vertical] before checking in views/shared
def partial_or_default(path_name, options={}, &block)
path_components = path_name.split("/")
file_name = path_components.pop
vertical_file_path = File.join(vertical}, path_components, file_name)
shared_file_path = File.join("shared", path_components, file_name)
full_vertical_file_path = File.join("#{Rails.root}/app/views/", "_#{vertical_file_path}.html.erb")
attempt_file_path = File.exist?(full_vertical_file_path) ? vertical_file_path : shared_file_path
render({:partial => attempt_file_path}.merge(options), &block)
end
【问题讨论】:
-
有什么原因不能使用
File.exists?来检查文件是否存在并呈现适当的文件?
标签: ruby-on-rails ruby-on-rails-3 partial-views actionview actionviewhelper