2016-05-31 76 views
0

我已經在我的應用程序中定義的以下關聯:ActiveRecord的查詢

class Person 
    belongs_to :type 
end 

class Type 
    has_many :people 
end 

現在,對於人的新的編輯形式,我需要給一個下拉菜單,將顯示所有的類型將來自類型模型。

現在有兩個辦法做同樣的:

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部分相同的任何好的解釋。

回答

0

與助手的想法是重用功能,例如格式化東西或提取複雜的邏輯。因此,如果這個查詢是你在許多情況下需要的東西,那麼在助手中使用它是一個好主意,在查詢執行中沒有真正的區別,更多是關於使用並且代碼更多清潔。