`
poppinhai
  • 浏览: 4815 次
社区版块
存档分类
最新评论

rails devise gem使用

阅读更多

最近一直在学习rails,学习了有大约一个月的时间了,前段时间看GEM的使用教程总是很费劲,最近自己静下心来,专心学习了一下GEM的使用,下面就介绍一下devise这个gem的使用。

进入项目

1、添加gem

   gem 'devise'

2、安装gem

   bundle install

3、创建一个页面方便我们测试是否成功

  rails g controller home index

4、初始化devise

  rails g devise:install

会有如下提示:

 

  1.   1. Setup default url options for your specific environment. Here is an

         example of development environment:

     

           config.action_mailer.default_url_options = { :host => 'localhost:3000' }

     

         This is a required Rails configuration. In production it must be the

         actual host of your application

     

      2. Ensure you have defined root_url to *something* in your config/routes.rb.

         For example:

     

           root :to => "home#index"

     

      3. Ensure you have flash messages in app/views/layouts/application.html.erb.

         For example:

     

           <p class="notice"><%= notice %></p>

           <p class="alert"><%= alert %></p>

     

      4. If you are deploying Rails 3.1 on Heroku, you may want to set:

     

           config.assets.initialize_on_precompile = false

     

         On config/application.rb forcing your application to not access the DB

         or load models when precompiling your assets.

5、创建user model

  rails g devise user

6、这样创建出来的user 模型只有注册邮件,密码的功能我们要给他加入用户名

   rails g migration add_name_to_users

这样我们就把他加入到了user model中

然后执行

rake db:migrate

7、产生视图模板

rails g devise:views

然后我们就可以订制我们自己的视图了

我们可以用

current_user方法获得session中的数据

8、生成index

rails g controller home index

 

修改index.html

<% if user_signed_in? %> <!-- Provided by devise -->
    <div style="float:right">
      <%= current_user.email %> |
      <%= link_to '用户信息', edit_user_registration_path %> |
      <%= link_to '退出登录', destroy_user_session_path, :method => :delete %> |
    </div>
    <% end %>
    <% unless user_signed_in? %>
    <div style="float:right">
      <%= link_to '注册', new_user_registration_path %> |
      <%= link_to '登录', new_user_session_path %>
    </div>
<% end %>

修改默认路由

root :to => "home#index"

 最后

rails s

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics