0

我想为两个模型(博客和帖子)使用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

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

4

1 回答 1

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
于 2012-01-23T21:46:28.827 回答