【发布时间】:2014-04-01 09:57:39
【问题描述】:
我正在尝试将 form_for 映射到特定的控制器和操作。我在路线中有resources: apikey。我发现的所有解决方案似乎都不起作用。表单放置在父文件夹名称与正确控制器不对应的视图中。这是我的表格,我的解决方案不起作用:
<%= form_for @key, url: { controller: :apikey, action: :update }, remote: true do |f| %>
<%= f.label :userkey, "Key" %>
<%= f.text_field :userkey %>
<%= f.submit "Update" %>
<% end %>
这是我的控制器:
class ApikeyController < ApplicationController
def index
end
def update
respond_to do |format|
if @key.update(apikey_params)
format.js
else
format.html { render action: 'edit' }
end
end
end
private
def apikey_params
params.require(:apikey).permit(:userkey)
end
end
这是我在控制台中得到的日志:
Started GET "/accounts?utf8=%E2%9C%93&_method=patch&apikey%5Buserkey%5D=thekey&commit=Update"
如您所见,它调用的不是 apikey,而是帐户控制器。我做错了什么?
更新
有点奇怪,因为我没有真正改变任何东西,现在打开网站时出现这个错误:
No route matches {:action=>"update", :controller=>"apikey"}
这是我的rake routes:
apikey_index GET /apikey(.:format) apikey#index
POST /apikey(.:format) apikey#create
new_apikey GET /apikey/new(.:format) apikey#new
edit_apikey GET /apikey/:id/edit(.:format) apikey#edit
apikey GET /apikey/:id(.:format) apikey#show
PATCH /apikey/:id(.:format) apikey#update
PUT /apikey/:id(.:format) apikey#update
DELETE /apikey/:id(.:format) apikey#destroy
更新 2 最初我在引导模式中有表单,如下所示:
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">Change API key</h4>
</div>
<div class="modal-body">
<form role="form">
<div class="form-group">
<%= form_for @key, method: "post", remote: true do |f| %>
<%= f.label :userkey, "Key" %>
<%= f.text_field :userkey, class:"form-control", id:"apikeyinputfield" %>
<%= f.submit "Update", class: "btn btn-success btn-sm" %>
<% end %>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" id="submitnewapikey" data-dismiss="modal" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
如果我删除了周围的模态,表单会自动映射到正确的控制器和动作。当被模态包围时,情况并非如此。真的很奇怪。也许模态的 JS 代码弄乱了 form_for JS 代码。
【问题讨论】:
标签: ruby-on-rails routing form-for