我在让这些多态关联完全工作时遇到了一些麻烦。我遵循了本教程www.railscasts.com/episodes/154-polymorphic-association,但这似乎只有在我发布新帖子时是路径 /controller/ID#/comments 时才有效。如果我尝试在 /controller/ID# 上呈现部分评论表单,我会在创建评论时收到此错误:
undefined method `comments' for #<ActiveSupport::HashWithIndifferentAccess:0x10341b2d0>
我有三个模型:
class Comment < ActiveRecord::Base
belongs_to :commentable, :polymorphic => true
end
class Post < ActiveRecord::Base
belongs_to :user
has_many :comments, :as => :commentable
end
class Article < ActiveRecord::Base
belongs_to :user
has_many :comments, :as => :commentable
end
这是我对 /articles/#{ID} 的看法
<%= @article.title %>
<%= @article.content %>
<%= @article.user.login %>
<%= link_to 'Edit Article', edit_article_path(@article) %>
<h2>Comments</h2>
<%= render "comments/comments" %>
<%= render "comments/comment" %>
这是我的部分评论:
<div class="post_comment">
<%= form_for [@commentable, Comment.new] do |f| %>
<%= f.text_area :content %>
<%= f.submit "Post" %>
<% end %>
</div>
这是我在评论控制器中的创建方法:
def create
@commentable = find_commentable
@comment = @commentable.comments.build(params[:comment])
@comment.user_id = current_user.id
if @comment.save
redirect_to :id => nil
else
flash[:notice] = "something went wrong"
redirect_to @commentable
end
end
def find_commentable
params.each do |name, value|
if name =~ /(.+)_id$/
return $1.classify.constantize.find(value)
end
end
end
我想我了解问题所在,但不确定如何解决问题。此表单正在寻找@commentable,但如果路径未嵌套,则无法找到@commentable(可能是错误的)。
这是我的路线:
devise_for :users do
get "login", :to => "devise/sessions#new"
get "register", :to => "devise/registrations#new"
end
resources :posts do
resources :comments
resources :tags
end
resources :articles do
resources :comments
resources :tags
end
resources :users do
resources :articles
resources :comments
resources :tags
resources :posts
end
resources :comments
root :to => "home#index"
end