我想在网址
提交表单/index/fruit
将表单数据提交到
/index/:identifier
其中:标识符由表单的值
确定此实例中的rails约定是什么? 有没有办法实现这一点,没有控制器级别重定向或javascript更新提交URL?
的routes.rb
match 'smasher(/:action(/:id))', :controller => "customcontroller", :as => :smasher, :defaults => { :action => :index, :id => :fruit }
index.html.erb
<%= semantic_form_for :d, :url => smasher_path, :html => { :method => :get } do |f| %>
... form data ...
<%= f.input :identifier, :as => :hidden %>
<% end %>
我目前的实施类似于this answer
答案 0 :(得分:1)
这并不是一个真正的“惯例”,而是有一种方法可以做到这一点。
你可以做到的一种方法仍然是将表单发送到控制器中的一个且只有一个操作,但是然后委托在控制器中执行哪个操作,如下所示:
def smasher
if params[:identifier] == 'this'
smash_this!
else
smash_that!
end
end
def smash_this!
# code goes here
end
def smash_that!
# code goes here
end
答案 1 :(得分:0)
下面是javascript版本(虽然技术上它只是在 erb html模板上),如果你对此感到满意。
<%= f.input :identifier, :as => :hidden, :onchange => "$(this).setAction()" %>
<script>
// While you can this script block here within your erb template
// but best practice says you should have it included somehow within `<head></head>`
$(function() {
//create a method on the Jquery Object to adjust the action of the form
$.fn.setAction = function() {
var form = $(this).parents('form').first();
var action = form.attr('action')
form.attr('action', action.substr( 0, action.lastIndexOf('/')+1 ) + $(this).val());
}
});
</script>
继承人纯javascript版本:
$(function() {
//create a method on the Jquery Object to adjust the action of the form
$.fn.setAction = function() {
var form = $(this).parents('form').first();
var action = form.attr('action')
form.attr('action', action.substr( 0, action.lastIndexOf('/')+1 ) + $(this).val());
}
//we gotta bind the onchange here
$('input[name="identifier"]').change($.fn.setAction);
});