簡體   English   中英

使用ruby on rails為用戶登錄創建一個count方法

[英]create a count method for user logins with ruby on rails

我想要的是:用戶登錄他的帳戶並自動更新自己的計數器(@counter + = 1)。

我是Ruby和Rails的新手,我使用的是Rails 3.2.12。 我讀了一本書“eloquent ruby​​”,搜索了有關這個問題的stackoverflow,並觀看了pragmaticstudio.com上的視頻 - 紅寶石課程。 在那個視頻課程中,他們創建了一個這樣的類:

class User < ActiveRecord::Base
  attr_accessible :name, :email, :password, :password_confirmation, :counter
  has_secure_password
  before_save { |user| user.email = email.downcase }
  before_save :create_remember_token

  def initialize(counter=0)
    @counter = counter
  end

  def w00t
    @counter += 15
  end

  private
    def create_remember_token
       self.remember_token = SecureRandom.urlsafe_base64
    end
end 

現在,在我的應用程序中,使用SessionsController解決了用戶登錄問題,這就是我的問題,因為來自User模型的每個方法對於SessionsController都是“未知的”。

class SessionsController < ApplicationController
  def new
  end

  def create
    user = User.find_by_email(params[:session][:email].downcase)
    if user && user.authenticate(params[:session][:password])
      sign_in user
      redirect_back_or templates_path
    else
      flash.now[:error] = 'something went wrong.'
      render 'new'
    end
  end

  def destroy
    sign_out
    redirect_to root_url
  end
end

這是我已經嘗試過的但是對我的解決方案不起作用:我補充道

user.w00t

在SessionsController中,1行以上

sign_in user

返回的錯誤是:“SessionsController的未定義的方法'w00t'”。

我還嘗試在Sessions Helper中編寫一個方法:

def woot(template)
  template.counter += 1    
end

然后我重新命令我的SessionsController'create'方法如下:

def create
    template = Template.find_by_bosskey(params[:bession][:bosskey])
    if template
      woot template                  #that is my new line !
      tsign_in template
      redirect_back_or template
    else
      flash.now[:error] = 'something went wrong.'
      render 'new'
    end
  end

有了這個,我沒有得到任何錯誤,但仍然計數器沒有改變。 我比以前更困惑。 請告訴我在哪里放置該方法或如何解決我的應用程序的這個問題我迷路了。

您的計數器沒有遞增,因為它沒有被持久化到數據庫。 您使用的實例變量僅對當前請求有效。 一旦重定向並重新加載頁面,該對象就會丟失到垃圾收集器以及計數器。

要使計數器持久化,您需要在用戶上創建一個新列來保存計數器,然后您可以使用Rails提供的增量方法。

# create the migration

rails g migration add_sign_in_count_to_users sign_in_count:integer
rake db:migrate

# Then increment

class User < ActiveRecord::Base
  def w00t
    increment! :sign_in_count
  end
end

ActiveRecord的::#持續增加!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM