Я пытаюсь объединить два 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
перед аранжировкой, но это также выдает и неопределенную ошибку. Я предполагаю, что проблема здесь в полиморфной ассоциации, но я не знаю, как это исправить.