1

我对 Rails 比较陌生,正在尝试使用评论来实现我的第一个多态关联。

我正在运行 rails 3.2.3

编辑 - 当我尝试发表评论时,我的日志返回此错误:

Started POST "/comments" for 127.0.0.1 at 2012-05-20 13:17:38 -0700
Processing by CommentsController#create as HTML
Parameters: {"utf8"=>"✓",     "authenticity_token"=>"SOLcF71+WpfNLtpBFpz2qOZVaqcVCHL2AVZWwM2w0C4=", "comment"=>{"text"=>"Test this comment"}, "commit"=>"Create Comment"}
User Load (0.3ms)  SELECT "users".* FROM "users" WHERE "users"."id" = 101 LIMIT 1
Completed 500 Internal Server Error in 126ms

NoMethodError (undefined method `Comment' for nil:NilClass):
app/controllers/comments_controller.rb:13:in `create'

我已经尝试了在 SO 和其他地方提供的许多不同的解决方案,包括下面 Jordan 的答案,我敢肯定,由于我自己的经验不足,但无法解决错误。

跟踪调用了 Comments Controller 中的第 13 行,我在下面的该行之后进行了注释以标记错误:

class CommentsController < ApplicationController
  def index
    @commentable = find_commentable
    @comments = @commentable.comments
  end

  def new
    @post = Post.find(params[:post_id])
  end

  def create
    @commentable = find_commentable
    @comment = @commentable.comments.build(params[:comment]) #<<<<LINE 13

    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

职位控制器:

def show
@post = Post.find(params[:id])

respond_to do |format|
  format.html  # show.html.erb
  format.json  { render :json => @post }
end
end

评论模板(在展后)

<ul id="comments">
  <% if @comments %>
     <h2>Comments</h2>
         <% @comments.each do |comment| %>
        <li><%= comment.text %></li>
      <% end %>
  <% else %>
       <h2>Comment:</h2>
  <% end %>
</ul>

<%= simple_form_for [@commentable,Comment.new], :html => { :class => 'form-horizontal', :multipart => true } do |f| %>
   <fieldset>
       <%= f.input :text %>
       Upload Photo <%= f.file_field :photo %>
  </fieldset>
  <div class="form-actions">
    <%= f.submit nil, :class => 'btn btn-primary' %>
  </div>
<% end %>

发布展示:

<p id="notice"><%= notice %></p>
<div class="row">
<div class="span2 offset1">
   <%= image_tag @post.photo.url(:show) %>
</div>
    <div class="span5">
            <h1><%= @post.title %></h1>
            <p><%= @post.index_text.html_safe %></p>
           <p><%= @post.show_text.html_safe %></p>
            <%= render "comments/comment" %>
            <%= render "comments/form" %>
            <% if can? :update, @course %>
                <%= link_to 'Edit Post', edit_post_path(@post), :class => 'btn btn-mini' %>
                <%= link_to 'Delete Post', @post, 
                                    confirm: 'Are you sure?', 
                                    method: :delete, 
                                    :class => 'btn btn-mini' %>
                 <%= link_to 'New Post', new_post_path, :class => 'btn btn-mini' %>
            <% end %>
     </div>

<nav class="span2 offset1">
    <ul class="well">
        <li>Category 1</li>
        <li>Category 2</li>
    </ul>
</nav>
</div>
<div class="row offset2">
    <%= link_to 'Back to Posts', posts_path, :class => 'btn btn-mini' %>
</div>

路线:

  resources :posts, :has_many => :comments
  resources :comments

很明显,有更多经验的人可以解决。让我知道是否有任何想法。布赖恩

4

3 回答 3

1

The problem is your find_commentable method.

Here are the params passed to your CommentsController#create:

Started POST "/comments" for 127.0.0.1 at 2012-05-20 13:17:38 -0700
Processing by CommentsController#create as HTML
Parameters: {"utf8"=>"✓",     "authenticity_token"=>"SOLcF71+WpfNLtpBFpz2qOZVaqcVCHL2AVZWwM2w0C4=", "comment"=>{"text"=>"Test this comment"}, "commit"=>"Create Comment"}

Here is your CommentsController#create:

def create
  @commentable = find_commentable
  @comment = @commentable.comments.build(params[:comment]) #<<<<LINE 13


def find_commentable
  params.each do |name, value|
    if name =~ /(.+)_id$/
      return $1.classify.constantize.find(value)
    end
  end

  nil
end

As you can see, find_commentable expects a param like xx_id (for example, comments_id) which it uses to search for an appropriate class (in case of comments_id, it will be Comment), otherwise it returns nil. Refer classify and constantize here.

Your params do not contain any such param. So, you always get a nil object.

Your find_commentable needs some rework. I think in case of nested_fields, it should be an expression like

/(.+)_attributes$/ 

instead of

/(.+)_id$/. 

And you need to have

:accepts_nested_attributes_for :commentable 

in your Comment model class.

于 2012-05-21T06:18:29.180 回答
1

问题是,@commentable就是nil,这意味着CommentsController#find_commentable正在返回nil。我认为您的正则表达式是正确的,因此这意味着发生了以下两件事之一find_commentable

  1. 没有params与您的正则表达式匹配的任何键。
  2. 您的正则表达式匹配,但结果表中没有任何 id 为value.

像往常一样通过检查params数据库中的记录来调试它,以确保它们看起来像您期望的那样。

于 2012-05-20T15:25:57.400 回答
0

我尝试了上述两个答案,但问题仍然存在。

我最终咨询了一位朋友,他提出了以下解决方案,我喜欢这个解决方案,因为它比我最初的尝试更优雅并且更易于阅读(稍后,当我或其他人需要返回代码时):

def find_commentable
  if params[:post_id]
    Post.find(params[:post_id])
  #elsif params[:other_id]
  #  Other.find(params[:other_id])
  else
    # error out?
  end
end

一旦我启动并运行它们,注释掉的部分将引用其他关联。

于 2012-05-22T16:25:48.747 回答