我的登录和注册表单都在同一页面上。我正在尝试根据填写的表格来指定应采用哪种“发布”路线。注册表单的帖子应该发送到create_user操作,登录表单的帖子应该发送到create动作。无论我在视图中指定什么,创建一些原因 - create_user操作 - 即使是登录表单。
路线:
get '/login' => 'sessions#new', as: :users
post '/login' => 'sessions#create_user'
post '/login' => 'sessions#create'
查看:
<div class="forms">
<div class="login">
<h3>Login</h3>
<%= form_for(:session, url: {action: "create"}) do |x| %>
<%= x.email_field :email, :placeholder => " Email", :style => "height:50px; width:350px; border: solid #ff4d4d; background-color:#eff5f5; margin-top:20px; padding-left:5px;" %>
<%= x.password_field :password, :placeholder => " Password", :style => "height:50px; width:350px; border: solid #ff4d4d; background-color:#eff5f5; margin-top: 35px; padding-left:5px;" %>
<%= x.submit "Login" %>
<% end %>
</div>
<div class="divide"></div>
<div class="signup">
<h3>Signup</h3>
<%= form_for @new_user, url: {action: "create_user"} do |x| %>
<%= x.text_field :name, :placeholder => " Name", :style => "height:50px; width:350px; margin-top:20px; border: solid #ff4d4d; background-color:#eff5f5; padding-left:5px;" %>
<%= x.email_field :email, :placeholder => " Email", :style => "height:50px; width:350px; margin-top:35px; border: solid #ff4d4d; background-color:#eff5f5; padding-left:5px;" %>
<%= x.password_field :password, :placeholder => " Password", :style => "height:50px; width:350px; margin-top:35px; border: solid #ff4d4d; background-color:#eff5f5; padding-left:5px;" %>
<%= x.submit "Submit" %>
<% end %>
</div>
</div>
控制器:
class SessionsController < ApplicationController
def new
@new_user = User.new
end
def create
@user = User.find_by_email(params[:session][:email])
if @user && @user.authenticate(params[:session][:password])
session[:user_id] = @user.id
redirect_to '/'
else
render '/login'
end
end
def create_user
@new_user = User.new(user_params)
if @new_user.save
session[:user_id] = @new_user.id
redirect_to '/'
else
render '/login'
end
end
def destroy
session[:user_id] = nil
redirect_to '/login'
end
private
def user_params
params.require(:user).permit(:name, :email, :password)
end
答案 0 :(得分:0)
你做得很奇怪,但这应该有效。 。
改变这个:
<%= form_for @new_user, url: {action: "create_user"} do |x| %>
对此:
<%= form_for @new_user, url: url_for(controller: 'sessions_controller', action: 'create_user') do |x| %>
您应该考虑将create user
内容移动到另一个控制器(UsersController)。如果您正确配置路线(添加resources :users
),则只需使用form_for @new_user
,而无需告知要发布的控制器/操作。