1
我想在我的應用上將兩個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
,但也引發和未定義的錯誤。我猜測多態關聯是這裏的問題,但我對如何解決這個問題不知所措。