0

我想爲兩個模型(博客和帖子)使用acts_as_commentable。我生成了評論模型並添加了所有的字段。如何爲兩個模型使用acts_as_commentable

我創建了一個comments_controller,並在創建動作我必須找到博客和帖子,所以對於工作我做這樣的事情: -

def create 
    if controller_name == "blogs" 
    @blog = Blog.find(params[:comment][:blog_id]) 
    @blog_comment = @blog.comments.new(:comment => params[:comment][:comment], :user_id => current_user.id) 
    if @blog_comment.save 
     flash[:success] = "Thanks for commenting" 
     redirect_to :back or root_path 
    else 
     flash[:error] = "Comment can't be blank!" 
     redirect_to :back or root_path 
    end 
    end 


    if controller_name == "topics" 
    @post = Post.find(params[:comment][:post_id]) 
    @post_comment = @post.comments.new(:comment => params[:comment][:comment], :user_id => current_user.id) 
    if @post_comment.save 
     flash[:success] = "Thanks for commenting" 
     redirect_to :back or root_path 
    else 
     flash[:error] = "Comment can't be blank!" 
     redirect_to :back or root_path 
    end 
    end 

我知道這是很醜陋,但我不不知道如何繼續這個,任何人都可以幫助我?

+2

http://railscasts.com/episodes/154-polymorphic-association – Shreyas

+0

@ShreyasSatish我沒有看到發佈前您的評論,你一定要加它作爲答案! – Damien

回答

0

我遇到了類似的問題,我的一個應用程序。

這裏是我做了什麼:

class CommentsController < ApplicationController 
    before_filter :get_commentable 

    def create 
    @comment = @commentable.comments.build(params[:comment]) 
    if @comment.save 
     ... 
    else 
     ... 
    end 
    end 

    private 
    def get_commentable 
     params.each do |k, v| 
     return @commentable = $1.classify.constantize.find(v) if k =~ /(.+)_id$/ 
     end 
    end 
end 
相關問題