ruby on rails and so on

当我们只建立了一个rails generate controller session,而没有建立一个model,那么在views部分

The main difference between this and the signin form is that we have no Session model, and hence no analogue for the @user variable. This means that, in constructing the new session form, we have to give form_for slightly more information; in particular, whereas

我们应该使用

<% provide(:title, "Sign in") %>
<h1>Sign in</h1>
<div class="row">
  <div class="span6 offset3">
    <%= form_for(:session, url: sessions_path) do |f| %>
      <%= f.label :email %>
      <%= f.text_field :email %>

      <%= f.label :password %>
      <%= f.password_field :password %>
      <%= f.submit "Sign in", class: "btn btn-large btn-primary" %>
    <% end %>
    <p>New user? <%= link_to "Sign up now!", signup_path %></p>
  </div>
</div>
        you might be able to guess that submitting this form will result in a params hash where params[:session][:email] and params[:session][:password] correspond to the email and password fields.当提交表单的时候,可以得到以下一个hash参数表。the submission results in a params hash containing the email and password under the key :session。当提交了的时候,会在params下面产生一个email和password的值


 Including the Sessions helper module into the Application controller. 
app/controllers/application_controller.rb

class ApplicationController < ActionController::Base
  protect_from_forgery
  include SessionsHelper
end

By default, all the helpers are available in the views but not in the controllers. We need the methods from the Sessions helper in both places, so we have to include it explicitly.在views中可以自动包含helper中的方法,但是如果是在controllers中必须要手动加上

转:

大家都知道controller中的params其实是一个Hash. 
一般params中的数据,从log可以看到如下的样式: 
Ruby代码  
Parameters: {"authenticity_token"=>"AOE3ui28pCMQpMuR77aY1EkoKVaAV1T05uep5to2X4Q=", "user"=>{"name"=>"yanghuan", "password_confirmation"=>"1234567", "password"=>"12345678"}}  

按照标准的Hash方法,应当这样使用: 
Ruby代码  
name = params["user"]["name"] # 请注意,用是的string,而不是symbal  
  
#但是一般我们都是使用symbal来访问的  
name = params[:user][:name]  


请看注意看到log的数据,params中的key是string而不是symbal 
Ruby代码  
h = {"name" =>'string'}  
h[:name] = 'symbal'  
puts h # => {"name"=>"string", :name=>"symbal"}  
#可见,"name" 与 :name 是两个不同的key  

但是在params中,我们可以使用symbal来访问,那是因为rails对params做了增强(我没有去看rails关于params的源代码) 

之前我一直没有留意这个细微的区别,直到有一天,我写下了如下代码: 
Ruby代码  
conditions = {}.merge(params)  
conditions.delete_if{|k,v| !v.is_a?(String) || v.eql?('') || %w{-1 0}.include?(v.to_s) || %w{action format controller commit page}.include?(k.to_s) }    
if conditions[:user][:name] == 'ooxx'  
  # 使用symbal是访问不了的...  
  # code ...  
end  


        Because HTTP is a stateless protocol, web applications requiring user signin must implement a way to track each user’s progress from page to page. One technique for maintaining the user signin status is to use a traditional Rails session (via the special session function) to store a remember token equal to the user’s id:
         session[:remember_token] = user.id
       This session object makes the user id available from page to page by storing it in a cookie that expires upon browser close. On each page, the application could simply call
        User.find(session[:remember_token])
to retrieve the user. Because of the way Rails handles sessions, this process is secure; if a malicious user tries to spoof the user id, Rails will detect a mismatch based on a special session id generated for each session.


如何做一个cookie

Finally, the create_remember_token method needs to assign to one of the user attributes, and in this context it is necessary to use the self keyword in front of remember_token:

private

def create_remember_token
  self.remember_token = SecureRandom.urlsafe_base64
end
然后在User中加入代码: before_save :create_remember_token 和以上private代码

cookies

We can use cookies as if it were a hash; each element in the cookie is itself a hash of two elements, a value and an optional expires date. 

用法如下:cookies[:remember_token] = { value:   user.remember_token,
                             expires: 20.years.from_now.utc }

1.year.from_now
  => Sun, 13 Mar 2011 03:38:55 UTC +00:00
  >> 10.weeks.ago
  => Sat, 02 Jan 2010 03:39:14 UTC +00:00

由于要实现20年的有效期这种用法在ruby on rails中非常普遍,所以我们为他特别制作了一个方法

cookies.permanent[:remember_token] = user.remember_token

等设好了之后就可以用这个来寻找用户了

User.find_by_remember_token(cookies[:remember_token])


def current_user=(user)
    @current_user = user
  end
 def current_user
    @current_user ||= User.find_by_remember_token(cookies[:remember_token])
  end

下面的这个函数用来页面第一次调用的calls the find_by_remember_token method the first time current_user is called,上面的是对赋值的重新定义


ruby 语法:

        啥是 #{name} 啊?这是 Ruby 用来往字符串中插入信息的方法。大括号里面的代码会被替换为评估后的字符串 。

     特别留意一下 @name,这是一个实例变量。类里面的任何函数都可以使用实例变量。

irb(main):024:0> class Greeter
irb(main):025:1>   def initialize(name = "World")
irb(main):026:2>     @name = name
irb(main):027:2>   end
irb(main):028:1>   def say_hi
irb(main):029:2>     puts "Hi #{@name}!"
irb(main):030:2>   end
irb(main):031:1>   def say_bye
irb(main):032:2>     puts "Bye #{@name}, come back soon."
irb(main):033:2>   end
irb(main):034:1> end
         实例变量是被隐藏起来的,但他们并不是被完全的隐藏起来。 当您检查一个对象的时候还是可以看到他们的。Ruby采用了面向对象的思想,将内部属性保护了起来。Greeter.instance_methods用来查看类的所有函数。如果我们只希望列出 Greeter 自己的函数,可以提供一个 false 参数给 instance_methods,表示我们不希望列出祖先类的函数。

         attr_accessor 会自动为我们定义两个新的函数, name 用来读取变量的值, name= 用来给变量赋值。

为了给特定的用户特定的权利,在操作之前我们要首先进行判断权限,那么下面的代码就讲了详细的流程

class UsersController < ApplicationController
  before_filter :signed_in_user, only: [:edit, :update]
  before_filter :correct_user,   only: [:edit, :update]
  .
  .
  .
  def edit
  end

  def update
    if @user.update_attributes(params[:user])
      flash[:success] = "Profile updated"
      sign_in @user
      redirect_to @user
    else
      render 'edit'
    end
  end
  .
  .
  .
  private

    def signed_in_user
      redirect_to signin_url, notice: "Please sign in." unless signed_in?
    end

    def correct_user
      @user = User.find(params[:id])
      redirect_to(root_path) unless current_user?(@user)
    end
end

为了做到当一开始你没登录,登入非允许页面的时候,必须先登录,然后登录成功后自动登入之前想去的页面的功能

module SessionsHelper
  .
  .
  .
  def redirect_back_or(default)
    redirect_to(session[:return_to] || default)
    session.delete(:return_to)
  end
  def store_location
    session[:return_to] = request.url
  end
end
这是在相应的Usercontroller中要修改的部分

private

    def signed_in_user
      unless signed_in?
        store_location
        redirect_to signin_url, notice: "Please sign in."
      end
    end
    def correct_user
      @user = User.find(params[:id])
      redirect_to(root_path) unless current_user?(@user)
    end

而真正用到的SessionController中,修改Create部分

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




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值