【发布时间】:2014-05-12 19:53:56
【问题描述】:
我使用与 cmets 的多态关联。当我尝试在显示模板中添加“编辑”和“销毁”时,标题中出现错误(现在只需编辑)。如何添加两个链接以显示?
cmets_controller.rb
class CommentsController < ApplicationController
....
before_action :signed_in_user, only: [:new, :edit]
before_filter :load_commentable
def index
@commentable = load_commentable
@comments = @commentable.comments
end
def show
end
def edit
@commentable = load_commentable
end
def new
@commentable = load_commentable
@comment = @commentable.comments.new
end
def create
@comment = @commentable.comments.new(comment_params)
@comment.user = current_user
if @comment.save
redirect_to @comment, notice: "Created."
else
render :new
end
end
def update
@comment = @commentable.comments.build(comment_params)
@comment.user = current_user
respond_to do |format|
if @comment.update(comment_params)
format.html { redirect_to @comment, notice: 'It was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: @comment.errors, status: :unprocessable_entity }
end
end
end
private
def load_commentable
resource, id = request.path.split('/')[1, 2]
@commentable = resource.singularize.classify.constantize.find(id)
end
....
end
show.html.erb 模板
<%= link_to "Edit", [:edit, @commentable, :comment] %>
表格
<%= form_for [@commentable, @comment] do |f| %>
....
日志
由 CommentsController 处理#显示为 HTML
参数:{"post_id"=>"1", "id"=>"2"}
评论加载 (0.3ms) SELECT "cmets".* FROM "cmets" WHERE "cmets"."id" = ?限制 1 [["id", "2"]]
Post Load (0.2ms) SELECT "posts".* FROM "posts" WHERE "posts"."id" = ?限制 1 [["id", "1"]]
用户负载 (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT 1 [["id", 2]]
(0.2ms) SELECT COUNT(*) FROM "cmets" WHERE "cmets"."user_id" = ? [["user_id", 2]] CACHE (0.0ms) SELECT COUNT(*) FROM "cmets" 在哪里“cmets”。“user_id”=? [["user_id", 2]]
在布局/应用程序中渲染 cmets/show.html.erb (10.7ms)
在 19 毫秒内完成 500 内部服务器错误ActionView::Template::Error (没有路由匹配 {:action=>"edit", :controller=>"cmets", :post_id=>#, :id=>nil, :format=>nil} 缺少必需的键:[:id]):
25: <div class="thumbsdown"><%= link_to image_tag('othericons/thumbiconDown.PNG', height: '20', width: '20'),“#”%>
26:
27:
28: 29:
30:
31:app/views/cmets/show.html.erb:28:in `_app_views_cmets_show_html_erb___2937579164590753686_69833853514120'Rendered /home/action/.rvm/gems/ruby-2.0.0-p247/gems/actionpack-4.0.0/lib/action_dispatch/middleware/templates/rescues/_trace.erb(1.6ms) 渲染 /home/action/.rvm/gems/ruby-2.0.0-p247/gems/actionpack-4.0.0/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb (1.2ms) 渲染 /home/action/.rvm/gems/ruby-2.0.0-p247/gems/actionpack-4.0.0/lib/action_dispatch/middleware/templates/rescues/template_error.erb 在救援/布局内 (19.1ms)
路线:
resources :posts do
resources :comments
end
【问题讨论】:
-
你能分享完整的错误堆栈跟踪吗?
-
我添加了它。你有什么看法?
-
感谢分享。您也可以从服务器日志中添加错误消息
ActionController::UrlGenerationError in Comments#show -
我也添加了。
-
很抱歉再次打扰您。我还需要从您的
routes.rb中查看您的路线
标签: ruby-on-rails ruby-on-rails-4