我再次坚持学习RoR,现在使用form_tag。我按照rails指南但无法将参数从form_tag传递给控制器。我的index.html.erb是:
<h1>Welcome to mySite.com</h1>
<p></p>
<p></p>
<%= form_tag(controller: "logins", method: "post") do %>
<p>
<%= label_tag(:username, "Username") %><br>
<%= text_field_tag(:username) %>
</p>
<p>
<%= label_tag(:password, "Password") %><br>
<%= password_field_tag(:password) %>
</p>
<p>
<%= submit_tag "create" %>
<%= submit_tag "clicked" %>
</p>
<% end %>
class LoginsController < ApplicationController
def index
end
def create
if params[:commit] == 'clicked'
render action: "clicked"
else
render text params.inspect
end
end
def clicked
render text: params.inspect
end
end
match "logins/index" => "logins#index", :as => :index , :via => [:get, :post]
#get "logins/create"
match "logins/create" => "logins#create", :as => :create ,:via => :get
#match "logins/clicked" => "logins#clicked", :as => :clicked, :via => [:get, :post]
get 'logins/clicked', to: 'logins#clicked'
#resources :logins
按钮点击index.html.erb刷新页面,就像把我带回索引页面一样。
更新:更新了评论中的建议。
由于 ABHI
答案 0 :(得分:1)
<h1>Welcome to mySite.com</h1>
<p></p>
<%= form_tag(controller: "logins", action: "create") do %>
<p>
<%= label_tag(:username, "Username") %><br>
<%= text_field_tag(:username) %>
</p>
<p>
<%= label_tag(:password, "Password") %><br>
<%= password_field_tag(:password) %>
</p>
<p>
<%=submit_tag "Create"%>
<%= submit_tag "Clicked" %>
</p>
<% end %>
class LoginsController < ApplicationController
def index
end
def create
if params[:commit] == "Clicked"
p "hi"
redirect_to clicked_logins_path(request.parameters)
else
render text: params.inspect + "hi"
end
end
def clicked
render text: params.inspect
end
end
在routes.rb
中resources :logins do
collection do
get 'clicked'
end
end
我希望它有所帮助。
答案 1 :(得分:0)
您需要在form_tag
中提交提交路径
<%= form_tag(clicked_login_path, method: "post" ) do %>
<p>
<%= label_tag(:username, "Username") %><br>
<%= text_field_tag(:username) %>
</p>
<p>
<%= label_tag(:password, "Password") %><br>
<%= password_field_tag(:password) %>
</p>
<p>
<%= submit_tag 'submit'%>
</p>