使用rails将表单信息保存到数据库中

时间:2015-08-08 02:58:53

标签: ruby-on-rails sqlite

我正在尝试提交表单以创建用户,但我在Powershell中看到只发送了一个GET请求,没有发送POST请求,因此数据库中没有任何内容。我正在为我的数据库使用rails 4.1.8,ruby 2.0.0和sqlite 3。

这是我第一次开发一些东西,非常感谢任何帮助!如果我还要包含其他内容,请告诉我们!

表单

的用户页面
<!DOCTYPE html>
<html>
<body>
<div class="container">
  <form class="form-signin">
        <h2 class="form-signin-heading">Sign Up For An Account</h2>
        <%=form_for(:user, :method => :post)  do |f|%>
        <%= f.text_field :first_name, :placeholder => 'First name' %>
        <%= f.text_field :last_name, :placeholder => 'Last name' %>
        <%= f.email_field :email, :placeholder => 'Email' %>
        <%= f.password_field :password, :placeholder => 'Password' %>
        <%=f.submit 'Sign Up', class: "btn btn-lg btn-primary btn-block"%>
        <%end%>
  </form>
</div>

</body>

</html>

用户控制器

class UsersController < ApplicationController
  def new
    @user = User.new
  end
  def create
    @user = User.new(user_params)
    if @user.save
      session[:user_id] = @user.id
      redirect_to '/dashboard'
    else
      redirect_to '/signup'
    end
  end
  private
  def user_params
    params.require(:user).permit(:first_name, :last_name, :email, :password)
  end
end

路线

Rails.application.routes.draw do
  root 'welcome#index'
  resources :users
  get '/signup' => 'users#new'
  get '/login' => 'sessions#new'
  post '/login' => 'sessions#create'
  delete '/logout' => 'sessions#destroy'
  get '/dashboard' => 'hours#new'
end

3 个答案:

答案 0 :(得分:1)

我认为这里的问题是你将form_for帮助器嵌套在另一个窗体中。 form_for助手生成一个完整的表单,包括外部标记。

您可以找到相关文档here

尝试将其更改为:

&#13;
&#13;
<div class="form-signin">
        <h2 class="form-signin-heading">Sign Up For An Account</h2>
        <%=form_for(:user, :method => :post)  do |f|%>
        <%= f.text_field :first_name, :placeholder => 'First name' %>
        <%= f.text_field :last_name, :placeholder => 'Last name' %>
        <%= f.email_field :email, :placeholder => 'Email' %>
        <%= f.password_field :password, :placeholder => 'Password' %>
        <%=f.submit 'Sign Up', class: "btn btn-lg btn-primary btn-block"%>
        <%end%>
  </div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

以下是更新且有效的用户页面

<!DOCTYPE html>
<html>
<body>
<div class="container">
        <h2 class="form-signin-heading">Sign Up For An Account</h2>
        <%=form_for(@user, url: users_path, method: :post) do |f|%>
        <%= f.text_field :first_name, :placeholder => 'First name' %>
        <%= f.text_field :last_name, :placeholder => 'Last name' %>
        <%= f.email_field :email, :placeholder => 'Email' %>
        <%= f.password_field :password, :placeholder => 'Password' %>
        <%=f.submit 'Sign Up', class: 'btn btn-lg btn-primary btn-block'%>
        <%end%>
</div>

</body>

</html>

答案 2 :(得分:0)

您还需要申报所有这些路线吗?如果你打电话给'rake routes',它们是不是已经存在了?如果不抱歉哈哈,请忽略这一点。