0

我已经阅读了我能找到的所有内容,但我仍然很难过。

我正在尝试使用 before_filter 来捕获未登录的用户,并将他们发送到另一个索引页面。这个想法是,登录的用户在点击 index.html.erb 时将看到他们自己的文章列表,未登录的用户将被重定向到列出文章但没有的 showall.html.erb 页面让他们阅读(并用一些广告打他们)。

我添加了一条路线:

资源:文章确实
得到“showall”
资源:评论
结束

'Rake routes' 显示路线 article_showall。我在views/articles 文件夹中有一个部分_showall.html.erb(它只包含文本'showall is working!')。如果我在另一个视图中渲染 showall(<%= render "showall" %>),它可以正常工作。

这是我的控制器的适用部分:

class ArticlesController < ApplicationController
skip_before_action :authorize, only: [:index, :show, :showall]
before_filter :require_user, :only => [:index]

def require_user
unless User.find_by(id: session[:user_id])
  render 'showall', :notice => "Please log in to read articles."
end
end

def index

@articles = current_user.articles

end

def showall
@articles = Article.all
end

当我运行它(未登录时)时,出现以下错误:

Missing template articles/showall, application/showall with....etc

我难住了。为什么我可以在视图中渲染“showall”,但是当我在控制器中引用它时出现 Missing Template 错误?预先感谢您的任何帮助!

4

3 回答 3

1

大卫和 user4703663 是对的。您的问题是您将模板命名为部分模板,但将其呈现为模板。您可以从文件名中删除下划线并保留代码原样,或者保留文件名原样并从索引视图中“渲染部分:'showall'”。

编辑:我应该补充一点,丢失的模板错误不应该在你心中灌输恐惧。它直接引导你犯错。不要强调它,下次尝试记住它的含义。它几乎总是一个错字,或者加载部分但将其命名为模板,反之亦然,或者忘记了相对路径的子文件夹或类似的东西。这很正常,口译员吐出这些错误是为了帮助你,而不是为了压迫你。

于 2015-06-13T15:28:49.447 回答
0

代替

render 'showall', :notice => "Please log in to read articles."

render :file => '/partial/showall', :notice => "Please log in to read articles."
于 2015-06-13T15:21:55.547 回答
0

太好了,解决了这个问题,现在它
为 nil:NilClass 返回未定义的方法 `each'

即使“showall”与“index”几乎相同。

于 2015-06-13T16:48:32.173 回答