您可能會考慮一個表格(帖子),但會從它繼承兩個子類(SitePost和MemberPost)。 這使您可以將大部分功能放入後期模型中。
你甚至可以把大部分的控制器功能到PostsController
然後,您可以有SitePostController和MemberPostController 2個控制器 - 從PostController的繼承......但對資源安全的具體要求不同before_filters 。
...實際上,你甚至可以用一個PostsController逃脫並讓這兩個子類中的每一個都有自己的「can_be_edited_by?」方法...在你的文章的成員方法的before_filter中被調用。只要確保帖子被實例化爲正確的類型 - 這可能需要一些路由魔法將「post_type」中的一些路由魔法分配給您的控制器。例如:
class Post < ActiveRecord::Base
...post-specific methods
end
class MemberPost < Post
def can_be_edited_by?(user)
... MemberPost-specific authorisation
end
end
class SitePost < Post
def can_be_edited_by?(user)
... SitePost-specific authorisation
end
end
class PostsController <...
before_filter :requires_login
before_filter :fetch_post, :only => [:edit, :update, :delete, :show]
before_filter :can_edit_post, :only => [:edit, :update, :delete, :show]
...
def can_edit_post
@post.can_be_edited_by?(current_user)
end
def fetch_post
post_class = (params[:post_type] || 'SitePost').constantize
@post = post_class.find(params[:id])
end
end
路由魔術(和任何錯誤)作爲練習留給讀者;)
謝謝,我很欣賞的意見。我想,我想知道這種方法是否有任何特別的好處。你的方法比使用2個表更方便。這是主要的好處嗎? – 2010-03-01 16:25:40
是的 - 這是主要的好處。 – 2011-11-22 09:15:42