gpt4 book ai didi

ruby-on-rails - 是否可以在 View Rails 中调用 ActiveRecord 方法

转载 作者:数据小太阳 更新时间:2023-10-29 07:49:31 24 4
gpt4 key购买 nike

使用 Rails 4

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

<%= Article.where(approved: true).count %>

<%= Article.where("short_answer is NOT NULL and short_answer != ''").count %>

我知道通常的做法是将它们存储在 Controller 内的实例变量中,但由于我使用的是局部变量,所以我不能这样做。

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

最佳答案

Is doing this ok? Can it hurt?

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

@instance_variables 被设置一次,并且可以在整个 View 中使用:

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

因为上面都使用了存储的@article数据,所以数据库只命中了一次(当@article在controller中创建的时候).

如果您在 View 中调用 AR 方法,基本上每次都会调用一个新的数据库:

#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]) %>

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

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

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

#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 %>

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

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

#app/views/shared/_partial.html.erb
<% approved ||= Article.approved_articles.size %>
<% short ||= Article.short_answer_presence.size %>

这将允许您根据需要设置局部变量,如果未设置,也可以设置“默认值”。

关于ruby-on-rails - 是否可以在 View Rails 中调用 ActiveRecord 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34377464/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com