【发布时间】:2010-10-21 17:32:48
【问题描述】:
下面我概述了多态关联的结构。
在 VacationsController 中,我将一些 cmets 内联描述了我当前的问题。但是,我想发布这个来看看我在这里的整个方法是否有点偏离。您可以在business_vacations_controller 和staff_vacations_controller 中看到,我必须为模型和控制器创建“getter”,以便我可以从vacations_model 中访问它们,这样我就知道我正在处理哪种类型的对象。虽然它有效,但它开始让人觉得有点可疑。
对于我要完成的工作,是否有更好的“最佳实践”?
型号
假期.rb
class Vacation < ActiveRecord::Base
belongs_to :vacationable, :polymorphic => true
end
企业.rb
class Business < ActiveRecord::Base
has_many :vacations, :as => :vacationable
end
员工.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
【问题讨论】:
标签: ruby-on-rails architecture polymorphism polymorphic-associations