问题
I am trying to roll together two Railscasts: http://railscasts.com/episodes/262-trees-with-ancestry and http://railscasts.com/episodes/154-polymorphic-association on my app.
My Models:
class Location < ActiveRecord::Base
has_many :comments, :as => :commentable, :dependent => :destroy
end
class Comment < ActiveRecord::Base
belongs_to :commentable, :polymorphic => true
end
My Controllers:
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
In my locations show view I have this code:
<%= render @comments %>
<%= render "comments/form" %>
Which outputs properly. I have a _comment.html.erb
file that renders each comment etc. and a _form.html.erb
file that creates the form for a new comment.
The problem I have is that when I try <%= nested_comments @comments %>
I get undefined method 'arrange'
.
I did some Googling and the common solution to this was to add subtree
before the arrange but that throws and undefined error also. I am guessing the polymorphic association is the problem here but I am at a loss as to how to fix it.
回答1:
Dumb mistake... forgot to add the ancestry gem and required migration which I thought I had already done. The last place I checked was my model where I eventually discovered my error.
来源:https://stackoverflow.com/questions/10369896/polymorphic-comments-with-ancestry-problems