【问题标题】:ActiveRecord query in views and helpers in RailsRails 中视图和助手中的 ActiveRecord 查询
【发布时间】:2016-09-29 14:14:03
【问题描述】:

我的应用程序中定义了以下关联:

class Person
  belongs_to :type
end

class Type
  has_many :people
end

现在,在 person 的新表单和编辑表单中,我需要提供一个下拉菜单,其中将显示来自 Type 模型的所有类型。

现在有两种方法可以做到这一点:

1. 在控制器中为类型创建一个实例变量并在表单视图中访问它。

class PeopleController 

  before_action :get_types, only: [:new, :create, :edit, :update]

  def new  
  end

  def create
  end

  def edit
  end

  def update
  end

  private

  def get_types
    @types = Type.all
  end

end

人/_form.html.erb

...
<%= f.select :type_id, @types.collect{ |type| [type.name, type.id]} %>
...

2。在 person_helper 中进行数据库查询

person_helper.rb

module PersonHelper
  def get_types
    Type.all
  end
end

人/_form.html.erb

...
<%= f.select :type_id, get_types.collect{ |type| [type.name, type.id]} %>
...


所以,我想知道哪种方法更好,为什么。

注意:根据 MVC 范例,控制器将向视图提供必要的数据。在这两种情况下,我都无法找到查询执行的任何差异,也无法找到除 MVC 部分之外的任何好的解释。

【问题讨论】:

    标签: ruby-on-rails activerecord model-view-controller


    【解决方案1】:

    帮助器的想法是重用功能,例如格式化某些东西或提取复杂的逻辑。

    因此,如果该查询是您在很多情况下都需要的东西,那么将它放在帮助程序中是个好主意,查询执行没有真正的区别,更多的是关于使用并且代码更干净.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-16
      • 2011-05-26
      • 2015-11-08
      • 1970-01-01
      • 1970-01-01
      • 2011-06-27
      • 2011-07-03
      • 1970-01-01
      相关资源
      最近更新 更多