我们有多个模型Post,Blog,Wiki和Comment。
在评论表中,我们维护了object_type,object_id和comment_type。
id object_type object_id comment_type
1 'Post' 1 'System'
2 'Blog' 2 'System'
3 'Wiki' 3 'User'
4 'Wiki' 4 'System'
/post/1/comments/:comment_type
/wiki/1/comments/:comment_type
要处理这个问题,我的路线应该如何,以及我应该创建多少个控制器来处理不同的注释类型?
答案 0 :(得分:1)
您可以从网址获取父模型:
before_filter :get_commentable
def create
@comment = @commentable.comments.create(comment_params)
respond_with @comment
end
private
def get_commentable
resource, id = request.path.split('/')[1,2]
@commentable = resource.pluralize.classify.constantize.find(id)
end
答案 1 :(得分:0)
至于此: /后/ 1 /评论/:comment_type
将资源嵌套为:
resources :posts do
resources :comments
end
给你:
post_comment_path GET /posts/:post_id/comments/:id(.:format) comments#show
你可以为其他资源做同样的事情。
更新:
关于选择comment_type,例如,处理它的一种方法是创建一个单独的模型。
class Comment
has_and_belongs_to_many :comment_types
end
class CommentType
has_and_belongs_to_many :comments
end
我使用的是simple_form,在你的new.html.erb表单中,你会这样做:
<%= f.association :comment_types %>
这会给你一个下拉菜单来选择comment_types。您可以在控制台中创建注释类型。说你只有:“系统”和“用户”comment_types。只需在控制台中创建它们,它们都会显示在下拉列表中供您选择。
如果采用此方法,则无需将资源嵌套在routes.rb文件中。