如何对两个模型使用acts_as_commentable

时间:2012-01-23 06:33:15

标签: ruby-on-rails ruby-on-rails-3.1 controller 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

我知道这很难看,但我不知道如何继续这个,有人可以帮帮我吗?

1 个答案:

答案 0 :(得分: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