我对 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
很明显,有更多经验的人可以解决。让我知道是否有任何想法。布赖恩