2011-03-27 65 views
0

得到了視圖和控制器驗證碼:滑軌從視圖中移動查詢到控制器

# matches/show.html.haml 
%h3 
    Players 

[email protected] do |clan| 
    %h4=link_to clan.name, clan 
    %ul 
    [email protected]_all_by_clan_id(clan.id).each do |player| 
     %li 
     %strong=link_to player.name, player 


%h3 
[email protected]_with_index do |round,index| 
    %h4 
    Round 
    =index+1 

    [email protected] do |clan| 
    %h4=clan.name 
    %ul 
     -round.participations.includes(:player,:champion).find_all_by_clan_id(clan.id).each do |participation| 
     %li 
      =participation.player.name 
      =participation.champion.name 

# matches_controller.rb 

class MatchesController < ApplicationController 
    def index 
    @matches = Match.played.includes(:clans).page(params[:page]) 

    end 

    def show 
    @match = Match.includes(:rounds,:clans).find(params[:id]) 
    @clans = @match.clans 
    @rounds = @match.rounds 

    @players = @match.players 

    end 
end 

如何移動所有不必要的數據庫查詢,邏輯等,從視圖控制器?
也許簡化這個莫名其妙?

回答

0

將它移動到匹配模型,而不是控制器。您的控制器通常應該只包含路由邏輯並設置一個實例變量以在視圖中使用。大部分代碼應該放在模型中。瘦身控制器,胖模特。

閱讀上的範圍:
http://edgerails.info/articles/what-s-new-in-edge-rails/2010/02/23/the-skinny-on-scopes-formerly-named-scope/index.html

此外,這篇文章是從2006年(預範圍),但大部分仍是有關你的問題:
http://weblog.jamisbuck.org/2006/10/18/skinny-controller-fat-model

你真不」不需要爲氏族,回合和玩家設置實例變量。在迭代相關集合的簡單情況下,您可以直接從@match訪問這些內容。例如:

[email protected] do |clan| 

否則,如果使用它的東西不是一個簡單的has_many更復雜/ belongs_to的關聯一個範圍。

相關問題