Rails:表单不保存到db,但create方法在提交时返回true

时间:2015-10-26 06:49:27

标签: ruby-on-rails ruby postgresql

我有一个简单的博客设置,其中包含资源路由,在允许用户查看博客之前对其进行身份验证。我能够#34;注册"通过" rails c"输入数据但是当尝试提交表单时,它不会保存到数据库并且"创建"方法返回true,就像它确实保存一样。

  

Controller:blogs_controller.rb

class BlogsController < ApplicationController

  before_action :confirm_logged_in, :except => [:login, :attempt_login, :new, :logout]

  def new
    @user = User.new
  end


  def create
  @user = User.new(message_params)
    if @user.save!
      redirect_to(:action => 'login')
    else
      render 'new'
    end
  end


  def login
  end


  def attempt_login
    if params[:email].present? && params[:password].present?
      found_user = User.where(:email => params[:email]).first
      if found_user
        authorized_user = found_user.authenticate(params[:password])
      end
    end
    if authorized_user
      session[:user_id] = authorized_user.id
      session[:email] = authorized_user.email
      redirect_to(:action => 'index')
    else
      redirect_to(:action => 'login')
    end
  end


  def index
  end

  def show_month
    @month_year = params[:month_year]
    @year = params[:year]
  end

  def show_category
    @category = params[:category]
  end

  def show_page
    @date = params[:date]
  end

  def logout
    session[:user_id] = nil
    session[:email] = nil
    flash[:notice] = "Logged out."
    redirect_to(:action => "login" )
  end


    private
  def message_params
    return params.require(:user).permit( :email, :password )
  end

  def confirm_logged_in
    unless session[:user_id]
      flash[:notice] = "Please login"
      redirect_to(:action => 'login')
      return false
    else
      return true
    end
  end

end
  

注册:new.html.erb

<div class="container-fluid">
  <div class="row">
    <div class="col-xs-12">
      <%= form_for @user, url: blogs_path(@user) do |f| %>
      <%= f.label :email %>
      <%= f.text_field :email, :required => true %>
      <br>
      <%= f.label :password %>
      <%= f.password_field :password, :required => true %>
      <br>
      <%= f.label :password_confirmation %>
      <%= f.password_field :password_confirmation, :required => true %>
      <br>
      <%= f.submit("Submit")%>
      <% end %>
    </div>
  </div>
</div>
  

型号:user.rb

class User < ActiveRecord::Base
  has_secure_password
end
  

架构:schema.rb

ActiveRecord::Schema.define(version: 20151026022639) do

  enable_extension "plpgsql"

  create_table "messages", force: :cascade do |t|
    t.string   "name"
    t.string   "email"
    t.string   "phone_number"
    t.string   "user_message"
    t.datetime "created_at",   null: false
    t.datetime "updated_at",   null: false
  end

  create_table "users", force: :cascade do |t|
    t.string   "email"
    t.string   "password_digest"
    t.datetime "created_at",      null: false
    t.datetime "updated_at",      null: false
  end

end
  

服务器日志:params

Started POST "/attempt_login" for ::1 at 2015-10-26 02:57:57 -0400
Processing by BlogsController#attempt_login as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"z4NgU41NLizqUE5vgXc44Q5n6VG36ho+5TVcPB4ixB7grZnCuwJY64+EWFzFIIJShbHEBNk3JutBuO4oalV2gQ==", "email"=>"chrispelnar@gmail.com", "password"=>"[FILTERED]", "commit"=>"Login"}
  User Load (0.3ms)  SELECT  "users".* FROM "users" WHERE "users"."email" = $1  ORDER BY "users"."id" ASC LIMIT 1  [["email", "chrispelnar@gmail.com"]]
Redirected to http://localhost:3000/blog_login
Completed 302 Found in 5ms (ActiveRecord: 0.3ms)
  

路由routes.rb

  get '/blog_signup'           => 'blogs#new'
  post 'blog_signup'           => 'blogs#create'
  get '/blog_login'            => 'blogs#login'
  post 'attempt_login'         => 'blogs#attempt_login'
  get '/blogs_home'            => 'blogs#index'
  get '/blog_month_archive'    => 'blogs#show_month'
  get '/blog_category_archive' => 'blogs#show_category'
  get '/blog_page'             => 'blogs#show_page'
  get '/logout'                => 'blogs#logout'

3 个答案:

答案 0 :(得分:1)

要做的很多修复 - 这就是我推荐的内容:

#config/routes.rb
root "posts#index"
resources :posts, only: [:index, :show]

resources :users, only: [:new, :create], path: "", path_names: { new: "signup", create: "signup" }
resources :sessions, only: [:new, :create, :destroy], path: "", path_names: { new: "login", create: "login", destroy: "logout" }

这会将您的控制器分成不同的动作。

这可能看起来很复杂,但相信我,从长远来看,它对你的应用来说会更好。

#app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
   #put all your application-centric logic here
   before_action :confirm_logged_in

   private

   def confirm_logged_in
      #don't need to "return" anything here
      redirect_to new_sessions_path, notice: "Please login" unless session[:user_id]
   end
end

而不是&#34;博客&#34;,称之为&#34;发布&#34;。您的应用程序逻辑保留在应用程序控制器中:

#app/controllers/posts_controller.rb
class PostsController < ApplicationController
   def index
      @posts = Post.all
   end

   def show
      @post = Post.find params[:id]
   end
end

这是为了处理用户会话(登录)(偷了这个form Devise):

#app/controllers/sessions_controller.rb
class SessionsController < ApplicationController
    skip_before_action :confirm_logged_in

    def new
    end

    def create
        if params[:email].present? && params[:password].present?
          if User.exists? email: params[:email]
               authorized_user = found_user.authenticate params[:password]
          end
        end
        if authorized_user
             session[:user_id] = authorized_user.id
             session[:email] = authorized_user.email
             redirect_to root_path, notice: "Successful Login"
        else
             redirect_to :new, notice: "Sorry, there was an error"
        end 
    end

    def destroy
        session.delete(:user_id)
        session.delete(:email)
        redirect_to new_sessions_path, notice: "Logged Out"
    end

end 
  

我能够#34;注册&#34;通过&#34; rails c&#34;输入数据但是在尝试提交表单时,它不会保存到db

以下是如何做到的:

#app/controllers/users_controller.rb
class UsersController < ApplicationController
   def new
      @user = User.new
   end

   def create
      @user = User.new user_params
      @user.save
   end

   private

   def user_params
      params.require(:user).permit(:email, :password, :other, :params)
   end
end

然后您就可以使用以下视图:

#app/views/users/new.html.erb
<%= form_for @user do |f| %>
  <%= f.email_field :email %>
  <%= f.password_field :password %>
  <%= f.password_field :password_confirmation %>
  <%= f.submit %>
<% end %>

-

顺便说一句,您使用Devise gem可以获得丰厚的利益。

这将基本上取消您应用中的所有session功能,包括Devise中的功能。这非常有效,我会高度推荐它。

答案 1 :(得分:0)

更改为:

private
def message_params
  params.require(:user).permit( :email, :password, :password_confirmation )
end

答案 2 :(得分:0)

  

问题出在控制器中:

before_action :confirm_logged_in, :except => [:login, :attempt_login, :new, :logout]
  

我错过了“:create”,这解决了这个问题:

before_action :confirm_logged_in, :except => [:login, :attempt_login, :new, :logout, :create]