0

下面我概述了多態關聯的結構。多態關聯的模型和控制器設計方法

在VacationsController中,我提出了一些內置註釋來描述我當前的問題。但是,我想發佈這個看看我的整個方法是否有點不合適。您可以在business_vacations_controller和staff_vacations_controller中看到我必須爲模型和控制器創建'getters',以便我可以從vacations_model內部訪問它們,以便知道我正在處理的是哪種類型的對象。雖然它有效,但它開始感覺有點可疑。

對於我想要完成的工作,有沒有更好的「最佳實踐」?

車型

vacation.rb

class Vacation < ActiveRecord::Base 
    belongs_to :vacationable, :polymorphic => true 
end 

business.rb

class Business < ActiveRecord::Base 
    has_many :vacations, :as => :vacationable 
end 

staff.rb

class Staff < ActiveRecord::Base 
    has_many :vacations, :as => :vacationable 
end 

business_vacation.rb

class BusinessVacation < Vacation 
end 

staff_vacation.rb

class StaffVacation < Vacation 
end 

控制器

business_vacations_controller.rb

class BusinessVacationsController < VacationsController 

    private 

    def controller_str 
     "business_schedules" 
    end 

    def my_model 
     BusinessVacation 
    end 

    def my_model_str 
     "business_vacation" 
    end 

end 

staff_vacations_controller.rb

class StaffVacationsController < VacationsController 

    private 

    def controller_str 
     "staff_schedules" 
    end 

    def my_model 
     StaffVacation 
    end 

    def my_model_str 
     "staff_vacation" 
    end 

end 

vacations_controller.rb

class VacationsController < ApplicationController 

    def create 
    # Build the vacation object with either an instance of BusinessVacation or StaffVacation 

    vacation = @class.new(params[my_model_str]) 

    # Now here's the current issue -- I want to save the object on the association. So if it's a 'BusinessVacation' object I want to save something like: 

    business = Business.find(vacation.vacationable_id) 
    business.vacations.build 
    business.save 

    # But if it's a 'StaffVacation' object I want to save something like: 

    staff = Staff.find(vacation.vacationable_id) 
    staff.vacations.build 
    staff.save 

    # I could do an 'if' statement, but I don't really like that idea. Is there a better way? 

    respond_to do |format| 
     format.html { redirect_to :controller => controller_str, :action => "index", :id => vacation.vacationable_id } 
    end 

    end 

    private 
    def select_class 
     @class = Kernel.const_get(params[:class]) 
    end 
end 

回答

0

感覺就像是很多籃球在VacationsController跳通過,使其認識到上下文的。是否有一個原因,StaffVacationsController和BusinessVacationsController不能每個都有一個#create動作,並且視圖會提交給哪個適當的?這些操作已經知道模型上下文,並能夠在之後重定向到適當的URL。

+0

是的,也許這是最好的解決方案。有很多沒有顯示的共享代碼,這就是爲什麼我在同一個控制器中擁有它,但也許這是我應該探索將它們分開的原因。 – 99miles 2010-10-21 22:54:54

+0

我想知道是否可能有一些共享代碼激發...有點難以調用沒有細節,但也許一些共享邏輯會進入Vacation模型和/或包含在控制器中的模塊? – njorden 2010-10-21 23:02:21