Rails:是否可以在视图中调用 ActiveRecord 方法 Rails

Kat*_*han 7 ruby methods activerecord ruby-on-rails ruby-on-rails-4

使用 Rails 4

我想知道(并且很难找到答案)是否可以直接从视图调用 ActiveRecord 方法,例如:

<%= Article.where(approved: true).count %>
Run Code Online (Sandbox Code Playgroud)

或者

<%= Article.where("short_answer is NOT NULL and short_answer != ''").count %>
Run Code Online (Sandbox Code Playgroud)

我意识到通常的做法是将这些存储在控制器内的实例变量中,但由于我使用的是部分,我不能这样做。

这样做好吗?能痛吗?有没有更好的方法来解决这个问题(例如辅助方法)?谢谢!

Ric*_*eck 6

这样做好吗?能痛吗?

这绝对没问题,但问题是您将调用另一个 db 查询 - 这是 Rails 应用程序中最“昂贵”的部分。

@instance_variables设置一次,可以在整个视图中使用:

#app/views/articles/show.html.erb
#Referencing @article references stored data, not a new DB query
<%= @article.title %>
<%= @article.description %>
<%= @article.created_at %>
Run Code Online (Sandbox Code Playgroud)

因为上面都使用存储的@article数据,所以数据库只命中一次@article在控制器中创建时)。

如果你在视图中调用 AR 方法,你基本上每次都会调用一个新的 db 调用:

#app/views/articles/show.html.erb
#Bad practice
<%= Article.select(:name).find(params[:id]) %>
<%= Article.select(:description).find(params[:id]) %>
<%= Article.select(:created_at).find(params[:id]) %>
Run Code Online (Sandbox Code Playgroud)

要直接回答您的问题,如果您只计算特定于数据库的数据,则可以调用该数据。

IE如果您要计算 的数量@articles,则可以调用@articles.size( ActiveRecord: size vs count )

谨慎的开发人员将确定他们在控制器中拥有哪些数据,以及他们需要从数据库中提取哪些数据……在控制器本身中完成所有数据库工作:

#app/controllers/articles_controller.rb
class ArticlesController < ApplicationController
   def index
      @articles = Article.where(approved: true) #-> could use a scope here if you wanted
   end
end

#app/views/articles/index.html.erb
<%= @articles.size %>
Run Code Online (Sandbox Code Playgroud)

Nithin的答案很好,但不会考虑您必须确定是否需要显式调用数据库或使用已调用的数据。

最后,关于使用部分,如果您每次都必须传递该数据,您可能希望使用某种条件数据来确定是否需要调用数据库:

#app/views/shared/_partial.html.erb
<% approved ||= Article.approved_articles.size %>
<% short    ||= Article.short_answer_presence.size %>
Run Code Online (Sandbox Code Playgroud)

这将允许您根据需要设置本地人,如果未设置,还可以设置“默认值”。