开发者

Trying to use polymorphic relationship between comments and models

I am follow开发者_StackOverflowing a railscasts guide ( http://asciicasts.com/episodes/154-polymorphic-association ) for making comments for different models, but I have run into a problem.

When I try to go to localhost:3000/articles/id/comments/new, I get the following error:

undefined method `comments_path' for #<#<Class:0xb608b40>:0xb607a60>

It is coming from my comment form:

1: <%= form_for([@commentable, @comment]) do |f| %>
2:   <%#= render 'shared/error_messages', :object => f.object %>
3:   <div class="field">
4:     <%= f.label :title %><br />

Here are the contents of the new method of the comments controller:

  def new
    @comment = Comment.new
  end

One thing that differs from the cast, my routes.db has this:

  resources :articles do
    resources :comments
  end

instead of this:

  resources :articles, :has_many => :comments

I get a routes error if I do not do it like this.

Any idea why? I know the guide is a little old, and I am on Rails 3.


You haven't assigned the @commentable variable in this your "new" action

it should be something like

  def new
    # This may need to change as per the class of the commentable field
    @commentable = Article.find(params[:article_id']
    @comment = Comment.new
  end


It looks like Rails doesn't like the combination of polymorphic and nested routes. I can't guarantee it will work, but try this:

<%= form_for([@commentable, @comment], :url => new_polymorphic_url([@commentable, @comment])) do |f| %>

Edit: You are missing the @commentable initialization that Rishav mentioned, so try that first.


Also, I find that I use "@commentable = find_commentable" in every comments controller method. Is there anyway to declare it once, and allow all the methods to have it?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜