我該怎麼幹?DRY me:Rails code
def correct_user
@company = RealEstateCompany.find(params[:id])
if(current_user != @company.user)
redirect_to(root_path)
end
end
def correct_user
@company = ConstructionCompany.find(params[:id])
if(current_user != @company.user)
redirect_to(root_path)
end
end
答案是下方,它是作爲遵循一個模塊中:
def correct_user_for_controller?(controller_name)
@company = controller_name.classify.constantize.find(params[:id])
redirect_to(root_path) unless (current_user == @company.user)
end
那麼任何控制器內包括的模型,並用
correct_user_for_controller?("ConstructionCompany")
correct_user_for_controller?("RealEstateCompany")
RealEstateCompany和ConstructionCompany是獨立的模型嗎?如果您只有一個公司模型,這將是DRYer。 – 2010-11-08 00:23:47
是RealEstateCompany與ConstructionCompany在幾個方面不同,例如ConstructionCompany has_many:項目,而RealEstateCompany則沒有。 – daniel 2010-11-08 00:44:51