我想两个Railscasts滚在一起: http://railscasts.com/episodes/262-trees-with-ancestry和http://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
的安排之前,但抛出和未定义的错误也。 在这里,我猜的多态关联的问题,但我在一个不知如何解决它。