【问题标题】:What routes to add in routes.rb for a controller create function?在 routes.rb 中为控制器创建功能添加哪些路由?
【发布时间】:2013-02-08 05:05:55
【问题描述】:

我的 chap_three_controller.rb 文件:

class ChapThreeController < ApplicationController
   def create
      @marker = Marker.new(params[:m])
      if @marker.save
         res={:success=>true,:content=>"<div><strong>found </strong>#{marker.found}
              </div><div><strong>left </strong>#{marker.left}</div>"}
      else
         res={:success=>false,:content=>"Could not save the marker"}
      end
      render :text=>res.to_json
   end
end

我的 routes.rb 文件

match '/map3', :to => 'chap_three#map'
match '/map3/create', :to => 'chap_three#:action'

我是否正确地将控制器中的创建函数与我的路由匹配?因为它不起作用..

这是我的 javascript 代码的 sn-p:

request.open('GET', 'create' + getVars, true);
 request.onreadystatechange = function() {
    if (request.readyState == 4) {
 //the request is complete
    var success=false;
    var content='Error contacting web service';
    try {
 //parse the result to JSON (simply by eval-ing it)
      res=eval( "(" + request.responseText + ")" );
      content=res.content;
      success=res.success;
    }catch (e){
       success=false;
     }

我不断收到的错误是“联系网络服务时出错”。这意味着我的 request.responseText 不起作用,并且我的控制器中的 create 方法没有做任何事情......任何帮助都会很棒

【问题讨论】:

    标签: ruby-on-rails routes controllers


    【解决方案1】:

    你希望你的比赛是:

    match '/map3/create' => 'chap_three#create'
    

    # 分别分隔控制器名称和动作名称,:to 是不必要的,仅在定义 root 路由时使用。我建议阅读Rails Routing Guide

    【讨论】:

    • 试图通过 @marker = Marker.new(params[:m]) 将 params[:m] 存储到数据库...但它不起作用..这是一个批量分配问题吗?想不通
    • 没关系,您添加到 URL 的任何查询参数都将在 params 中可用。因此,如果您的 URL 是 /map3/create?m[left]=some_value&amp;m[found]=true,那么 params[:m] 将具有 leftfound 的值。
    • 可能是批量分配问题。确保您发送的值具有 attr_accessible。您还可以检查 @marker.save 是否正在返回 false,如果是,请检查 @marker.errors 以了解它失败的原因。您也可以将其切换到@marker.save!,这将引发异常,并可能在您的调试过程中使其更加明显。
    • 我检查了服务器输出,值与您所说的一致,m 将所有值保存为哈希...。但它没有存储在数据库标记中...任何知道为什么会发生这种情况?它显示 Active_Record:0.0ms
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-20
    • 2012-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多