如何在 Ruby on Rails 中使用应用程序助手
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/477114/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use Application Helpers in Ruby on Rails
提问by Chris Stewart
I'm attempting to post a random testimonial on each page of a site.
我试图在网站的每个页面上发布随机推荐。
I started off by using an application helper like this:
我开始使用这样的应用程序助手:
module ApplicationHelper
def random_testimonial
@random_testimonial = Testimonial.find(:first, :offset => rand(Testimonial.count))
end
end
In my view I can reference the method but it's being called on each reference, which makes sense.
在我看来,我可以引用该方法,但在每个引用上都会调用它,这是有道理的。
I'd like this to be called once on each page view exposing a Testimonial object I can use within the view.
我希望在每个页面视图上调用一次,公开一个我可以在视图中使用的 Testimonial 对象。
What should I be looking for to do this?
我应该寻找什么来做到这一点?
回答by Scott Miller
While that works, and I have certainly been known to do this, it violates the MVC separation of concerns. View helpers are not supposed to contain controller/model type logic, which this does.
虽然这有效,而且我当然知道这样做,但它违反了 MVC 关注点分离。视图助手不应该包含控制器/模型类型逻辑,而这样做。
You might consider refactoring this back into the application controller. Helpers are supposed to be for view formatting and stuff, more than as a function (which is what I kept wanting to do when I got started.)
您可以考虑将其重构回应用程序控制器。Helpers 应该用于视图格式和其他东西,而不是作为一个函数(这是我开始时一直想做的事情。)
If you got back into your Testimonail model, do could do
如果你回到你的 Testimonail 模型,做可以做
def self.random
Testimonial.find(:first, :offset => rand(Testimonial.count))
end
then in your application controller, you could do:
然后在您的应用程序控制器中,您可以执行以下操作:
def random_testimonial
@random_testimonial ||= Testimonial.random
end
and call it from a before_filter
并从 before_filter 调用它
This has the advantage of moving the database logic back into the model where it belongs.
这具有将数据库逻辑移回其所属模型的优点。
回答by Milan Novota
If I understand you correctly, you want a method that returns the same object every time it is referenced in one request/response cycle. If this is true, you can achieve it with a minor change to your helper:
如果我理解正确,您需要一种方法,每次在一个请求/响应周期中引用它时都返回相同的对象。如果这是真的,您可以通过对您的助手稍作更改来实现它:
def random_testimonial
@random_testimonial ||= Testimonial.find(:first, :offset => rand(Testimonial.count))
end
Notice the "||=" part. That's a Ruby idiom which says: assign a value to @random_testimonial, unless it already has a value.
注意“||=”部分。这是一个 Ruby 习语,它说:为@random_testimonial 分配一个值,除非它已经有一个值。
Hope that answers your question.
希望这能回答你的问题。

