带有祖先问题的多态性评论

时间:2012-04-29 05:19:25

标签: ruby-on-rails-3 polymorphic-associations ancestry

我正在尝试在我的应用上合并两个Railscast:http://railscasts.com/episodes/262-trees-with-ancestryhttp://railscasts.com/episodes/154-polymorphic-association

我的模特:

class Location < ActiveRecord::Base
  has_many :comments, :as => :commentable, :dependent => :destroy
end

class Comment < ActiveRecord::Base
  belongs_to :commentable, :polymorphic => true
end

我的控制器:

class LocationsController < ApplicationController
      def show
        @location = Location.find(params[:id])
        @comments = @location.comments.arrange(:order => :created_at)

        respond_to do |format|
          format.html # show.html.erb
          format.json { render json: @location }
        end
      end
end

class CommentsController < InheritedResources::Base

  def index
    @commentable = find_commentable
    @comments = @commentable.comments.where(:company_id => session[:company_id])
  end

  def create
    @commentable = find_commentable
    @comment = @commentable.comments.build(params[:comment])
    @comment.user_id = session[:user_id]
    @comment.company_id = session[:company_id]
    if @comment.save
      flash[:notice] = "Successfully created comment."
      redirect_to :id => nil
    else
      render :action => 'new'
    end
  end

  private

  def find_commentable
    params.each do |name, value|
      if name =~ /(.+)_id$/
        return $1.classify.constantize.find(value)
      end
    end
    nil
  end

end

在我的位置展示视图中,我有以下代码:

<%= render @comments %>
<%= render "comments/form" %>

哪个输出正常。我有一个_comment.html.erb文件,用于呈现每个评论等,还有一个_form.html.erb文件,用于创建新评论的表单。

我遇到的问题是,当我尝试<%= nested_comments @comments %>时,我会undefined method 'arrange'

我做了一些谷歌搜索,对此的常见解决方案是在排列之前添加subtree,但也会抛出和未定义的错误。我猜这里的多态关联是问题,但我对如何解决它感到茫然。

1 个答案:

答案 0 :(得分:0)

愚蠢的错误......忘记添加祖先宝石和所需的迁移,我认为我已经做过了。我检查的最后一个地方是我的模型,我最终发现了我的错误。