简体   繁体   English

Rails 3-从视图中调用模型方法

[英]rails 3 - calling model methods from the view

I have a model and in the view I simply want to fetch a random instance of the model in my db and display its name. 我有一个模型,在视图中,我只想在数据库中获取该模型的随机实例并显示其名称。 Do both approaches below work? 下面两种方法都行吗? If so, which one is recommended: 如果是这样,建议使用以下哪个:

GET /random GET /随机

1) 1)


random.html.erb random.html.erb

<%= Foo.random.name %>

2) 2)


application_controller.rb application_controller.rb

def random
  @name = Foo.random.name
end

random.html.erb random.html.erb

<%= @name %>

I recommend 2): By isolating all of your data access in the controller, rather than spreading it around in your views, it becomes much easier too see what data your views need. 我建议2):通过隔离控制器中的所有数据访问权限,而不是在视图中分散访问权限,查看视图所需的数据也变得容易得多。 That makes it easier to refactor. 这使得重构更加容易。 Minimizing logic & data access in your views is an MVC best practice. 在您的视图中最小化逻辑和数据访问是MVC的最佳做法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM