将JS变量传递给Rails中的控制器

时间:2015-08-10 11:43:10

标签: javascript ruby-on-rails controller routes

我发现了这个:Passing javascript variables to rails controller

......我一直试图做同样的事情,即

window.open("http://localhost:3000//controller/index?location="+location,"_self")

我的控制员:

class FindMeController < ApplicationController
  def index
    location = params[:location]
    @snake = Snake.where(location: location)
    if @snake.save
        redirect_to root_url
    else
        redirect_to root_url
  end
end

但是,我总是得到“没有路线匹配错误”#39;我知道这可能很简单,但我还没理解如何修复它。

我尝试更改控制器&#39;在window.open行中显示实际的控制器名称 - &#39; find_me_controller&#39;但那并没有奏效。我也尝试省略localhost,只是做了&#39; / controller ...&#39;但这也没有帮助。

有人可以解释这个错误意味着什么,以及我如何解决它。

感谢。

编辑:

好的,我已将此添加到routes.rb:

获取&#39; FindMeController / index&#39;,以:&#39; find_me_controller #index&#39;

现在就行了 window.open("http://localhost:3000//FindMeController/index?location="+countryLoc+",_self")

...但现在我有一个新错误:未初始化的常量FindMeControllerController

此外,rake路线没有给出:

FindMeController_index GET /FindMeController/index(.:format)find_me_controller #index

EDIT2:

我已经销毁了find_me控制器并生成了一个蛇控制器并复制了旧的索引操作,但现在还有一堆错误。它说&#39; home / samuel / Code / VenomApp / VenomRails / app / controllers / snakes_controller.rb:10:语法错误,意外的输入结束,期待keyword_end&#39;对于我的控制器:

class SnakesController < ApplicationController
  def index
    location = params[:location]
    @snake = Snake.where(location: location)
    if @snake.save
        redirect_to root_url
    else
        redirect_to root_url
  end
end

我不明白。为什么它会进入我的控制器而不是我的蛇#index view ???

2 个答案:

答案 0 :(得分:1)

将此http://localhost:3000//controller/index?location=&#34; +位置,&#34; _self更改为&#34; http://localhost:3000/controller/index?location=&#34; +位置+&#34;,_ self&#34;

答案 1 :(得分:1)

在控制台上尝试rake路由,找出FindMecontroller索引操作的路径并替换该路由,即

window.open(&#34;&lt;%= your_path%&gt;&#34; +&#34; /&#34; +&#34;您的变量&#34;)