<%= form_tag('add_person', method: 'get') do %>
<%= label_tag(:name, 'Name') %>
<%= text_field_tag(:name) %>
<%= submit_tag 'Add new person' %>
<% end %>
<%= def add_person
if params[:name] == "John")
enter code here
else
enter code here
end
end %>
How do I make the submit button call the function add_person? I'm using Ruby/Rails
如何让提交按钮调用add_person函数?我正在使用Ruby / Rails
1 个解决方案
#1
3
Calling one or more methods via submit button:
通过提交按钮调用一个或多个方法:
The form_tag helper determines the controller method to be called:
form_tag帮助程序确定要调用的控制器方法:
<%= form_tag('controller/controller_method', method: 'put') do %>
The submit_tag passes a value to the controller where it's evaluated.
submit_tag将值传递给评估它的控制器。
<%= submit_tag "Add Person" %>
In the controller, you branch based on the value passed by your submit button:
在控制器中,您可以根据提交按钮传递的值进行分支:
def controller_method
if params[:commit] == "Add Person"
add_person
elsif params[:commit] == "Method 2"
method_2
elsif params[:commit] == "Method 3"
method_3
end
end
Calling method via arbitrary button
通过任意按钮调用方法
You probably have something like this at the bottom of your form:
您可能在表单底部有这样的内容:
<div class="actions">
<%= f.submit %>
</div>
which can be replaced with the button_to
helper, like so:
可以用button_to帮助器替换,如下所示:
<%= button_to "Submit", :method=> 'add_person' %>
Your add_person
method would have to be defined in the controller for the object to which your form refers.
您的add_person方法必须在控制器中为表单引用的对象定义。
#1
3
Calling one or more methods via submit button:
通过提交按钮调用一个或多个方法:
The form_tag helper determines the controller method to be called:
form_tag帮助程序确定要调用的控制器方法:
<%= form_tag('controller/controller_method', method: 'put') do %>
The submit_tag passes a value to the controller where it's evaluated.
submit_tag将值传递给评估它的控制器。
<%= submit_tag "Add Person" %>
In the controller, you branch based on the value passed by your submit button:
在控制器中,您可以根据提交按钮传递的值进行分支:
def controller_method
if params[:commit] == "Add Person"
add_person
elsif params[:commit] == "Method 2"
method_2
elsif params[:commit] == "Method 3"
method_3
end
end
Calling method via arbitrary button
通过任意按钮调用方法
You probably have something like this at the bottom of your form:
您可能在表单底部有这样的内容:
<div class="actions">
<%= f.submit %>
</div>
which can be replaced with the button_to
helper, like so:
可以用button_to帮助器替换,如下所示:
<%= button_to "Submit", :method=> 'add_person' %>
Your add_person
method would have to be defined in the controller for the object to which your form refers.
您的add_person方法必须在控制器中为表单引用的对象定义。