【发布时间】: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