I am having a bit of trouble getting these polymorphic associations to work completely. I followed this tutorial www.railscasts.com/episodes/154-polymorphic-association, but that seems to only work if I am path /controller/ID#/comments when making a new post. If I try to render a partial comment form right on /controller/ID# I get this error when creating the comment:
undefined method `comments' for #<ActiveSupport::HashWithIndifferentAccess:0x10341b2d0>
I have three models:
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
And this is my view for /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" %>
And here is my comment partial:
<div class="post_comment">
<%= form_for [@commentable, Comment.new] do |f| %>
<%= f.text_area :content %>
<%= f.submit "Post" %>
<% end %>
</div>
Here is my create method in the comments controller:
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
I think I understand what the issue is, but not sure how to correct the problem. This form is looking for @commentable, but if the path isn't nested it cannot find @commentable (may be wrong).
Here are my routes:
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