行动问题的链接

时间:2009-11-11 07:49:53

标签: ruby-on-rails

我的申请有问题。

我有表格报告,有2列,user_id和comment_id 我在文章评论视图上创建了链接

<%= link_to "[ ! ]", report_comment_url(comment) %>

class CommentsController < ApplicationController

  def report
    @comment = Comment.find(params[:id])
    @comment = CommentReport.new(params[:comment_report, :comment_id])
    if @comment_report.save
      redirect_to :back
    end
    redirect_to :back
  end
end

但是错误

的ActionController :: MethodNotAllowed

只允许发帖请求。

您是否有任何建议如何将current_user id和comment_id发布到报告表?

3 个答案:

答案 0 :(得分:0)

鉴于我认为你想要完成的事情,我建议你使用link_to_remote。

答案 1 :(得分:0)

这是发生了什么:

使用Restful路线,您已将报告设置为后期操作。这似乎是合理的,因为报告正在执行创建操作。

不幸的是,link_to不知道甚至不关心它。通常,链接仅执行获取请求。表单生成帖子请求,但在这种情况下它们似乎是不必要的。

您有四种选择。

  1. 制作[! ]链接提交报告的表单上的按钮。

  2. 中断RESTful指南并重新定义报告接收请求。

  3. 将此设为link_to_remote。注:这依赖于javascript,如果禁用Javascript,则根本不起作用。

  4. 将方法选项添加到link_to调用。注:这也依赖于javascript,如果禁用了javascript,它将回退到get请求。

    <%= link_to "[ ! ]", report_comment_url(comment), :method => :post %>
    
  5. 然而,这些解决方案都不能解决您的所有问题。你发布的代码有一些错误,你可能还没有意识到。

    首先:

    @comment = CommentReport.new(params[:comment_report, :comment_id])
    

    语法错误,会失败。有很多方法可以解决这个问题,首选的方法是将:comment_id滚动到params [:comment_report]哈希来解决这个问题。

    即将params传递给:

    params = {
      :id => 4,  # done by report_comment_url
      :comment_report => {
         :attribute1 => value1,
         ...
         :comment_id => 4
      }
    }
    

    现在你可以使用

    @comment = CommentReport.new(params[:comment_report])
    

    达到预期的效果。

    第二: report_comment_url不传递其他参数,因此您的控制器将尝试保存空记录。将comment_report添加到report_comment_url的参数将解决此问题。

    这将执行一个远程调用,在comments控制器中请求报告操作,并使用参数hash来解决另一个问题。

     <%= link_to_remote "[ ! ]", report_comment_url(comment, 
       :comment_report => {:attribute1 => value1, ..., :comment_id => comment.id}),
       :method => :post %> 
    

答案 2 :(得分:0)

params [:comment_report]为nil,因为在link_to语句中没有引用它。由于您在评论中提到您的观点是:

<%= link_to "[ ! ]", report_comment_url(comment), :comment_id => comment.id, :user_id => comment.user_id %>

然后你需要在控制器中使用它:

@comment_report = CommentReport.new(:user_id => params[:user_id], :comment_id => params[:comment_id]) 

但我同意NSD的观点,即link_to_remote可以更好地完成您想要完成的任务(创建新记录并将用户返回到页面)。您也可以不再使用@comment = Comment.find(params [:id])语句。