为什么我的' POST'请求不要调用我的方法,即使它发送了什么?

时间:2014-04-07 06:44:56

标签: jquery ruby-on-rails ruby ajax post

我正在尝试为控制器方法请求“POST”,如下所示:

$.ajax({type: "POST", url: something, data: {to_find_id: 978636122}, success:function(){ }});

它发送我的数据,显示以下日志:

Started POST "/thingys/519716477/do_something" for 127.0.0.1 at 2014-04-03 14:54:44 +0200
Processing by ThingysController#do_something as */*
  Parameters: {"to_find_id"=>"978636122", "thingy_id"=>"519716477"}
  ←[1m←[36mUser Load (0.0ms)←[0m  ←[1mSELECT "users".* FROM "users" WHERE "users"."id" =? LIMIT 1←[0m  [["id", 702273327]]
Redirected to http://localhost:3000/
Completed 302 Found in 0ms (ActiveRecord: 0.0ms)

302 Found的简短说明: WIKIPEDIA-LINK

我的方法:

def do_something
  Something.create(timespan_id: params[:to_find_id].to_s, thingy_id: @thingy.id)
  respond_to do |format|
    format.js {render :nothting => true}
  end
end

我已经在routes.rb - 文件中定义了我的方法。

resources :thingys do
  post 'do_something'
  post 'undo_something'
end

所以它发送请求,甚至找到方法。

你知道吗,我该怎么做才能让它发挥作用?


编辑:

我添加了我的真实性令牌,但我仍然无法访问我的方法。

Here is what I get now:
Started POST "/thingys/519716477/add_something?&authenticity_token=1l3tTWfwNgt56lp93w2QghUJvUYZn87V/8Zs7Fcrijq+8=" for 127.0.0.1 at 2014-04-07 13:04:15 +0200
Processing by ThingysController#add_something as */*
  Parameters: {"to_find_id"=>"310026847", "authenticity_token"=>"1l3tTWfwNgt56lp93w2QghUJvUYZn87V/8Zs7Fcrijq 8=", "subgroup_id"=>"519716477"}
  ←[1m←[35mUser Load (0.5ms)←[0m  SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1  [["id", 702273327]]
  ←[1m←[36mThingyp Load (0.5ms)←[0m  ←[1mSELECT "subgroups".* FROM "thingys" WHERE "thingys"."id" = ? LIMIT 1←[0m  [["id", "519716477"]]
Redirected to http://localhost:3000/
Completed 302 Found in 22ms (ActiveRecord: 1.0ms)

我还在我的应用程序控制器中添加了protect_from_forgery with: :exception,在我的ThingysController中添加了skip_before_filter:verify_authenticity_token

2 个答案:

答案 0 :(得分:1)

你无法在rails中发送POST参数而没有真实性令牌。

请参阅本页中的CSRF对策: http://guides.rubyonrails.org/security.html

或者这个帖子 Understanding the Rails Authenticity Token

答案 1 :(得分:0)

我假设"没有工作"表示操作未执行您期望的任务,即创建Something实例。如果我不得不猜测,某些东西未能通过模型​​上定义的验证。这将阻止模型保存。

您可以尝试:Something.create!(attrs),如果验证失败会引发错误,从而更清楚地说明为什么它不会保存。

要使其正常工作,您只需要保存有效的Something,无论这对您的应用程序意味着什么。


你也有拼写错误

format.js {render :nothting => true}
#                      ^ typo!