王筝的博客
ruby学习

(1)新增gem

gem 'devise'

 

(2)添加devise配置文件

/workspace/shop:$ rails generate devise:install User
      create  config/initializers/devise.rb
      create  config/locales/devise.en.yml
===============================================================================

Some setup you must do manually if you haven't yet:

  1. Ensure you have defined default url options in your environments files. Here
     is an example of default_url_options appropriate for a development environment
     in config/environments/development.rb:

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

     In production, :host should be set to 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 on Heroku with Rails 3.2 only, 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. You can copy Devise views (for customization) to your app by running:

       rails g devise:views

===============================================================================

(3) 添加一个user的model

/workspace/shop:$ rails generate devise User
      invoke  active_record
      create    db/migrate/20151026095446_devise_create_users.rb
      create    app/models/user.rb
      invoke    rspec
      create      spec/models/user_spec.rb
      insert    app/models/user.rb
       route  devise_for :users

(4) 安装devise视图文件

/workspace/shop:$ rails g devise:views
      invoke  Devise::Generators::SharedViewsGenerator
      create    app/views/devise/shared
      create    app/views/devise/shared/_links.html.erb
      invoke  form_for
      create    app/views/devise/confirmations
      create    app/views/devise/confirmations/new.html.erb
      create    app/views/devise/passwords
      create    app/views/devise/passwords/edit.html.erb
      create    app/views/devise/passwords/new.html.erb
      create    app/views/devise/registrations
      create    app/views/devise/registrations/edit.html.erb
      create    app/views/devise/registrations/new.html.erb
      create    app/views/devise/sessions
      create    app/views/devise/sessions/new.html.erb
      create    app/views/devise/unlocks
      create    app/views/devise/unlocks/new.html.erb
      invoke  erb
      create    app/views/devise/mailer
      create    app/views/devise/mailer/confirmation_instructions.html.erb
      create    app/views/devise/mailer/reset_password_instructions.html.erb
      create    app/views/devise/mailer/unlock_instructions.html.erb

(5)生成下表

/workspace/shop:$ rake db:migrate
== 20151026095446 DeviseCreateUsers: migrating ================================
-- create_table(:users)
   -> 0.0312s
-- add_index(:users, :email, {:unique=>true})
   -> 0.0004s
-- add_index(:users, :reset_password_token, {:unique=>true})
   -> 0.0004s
== 20151026095446 DeviseCreateUsers: migrated (0.0322s) =======================

(6)导航栏增加登录 注册的入口app/views/layouts/application.html.erb

          <ul class="nav navbar-nav navbar-right">
            <% if user_signed_in? %>
              <li><%= link_to current_user.email, profile_path %></li>
              <li><%= link_to "退出", destroy_user_session_path, method: :delete %></li>
            <% else %>
              <li><%= link_to "登录", new_user_session_path %></li>
              <li><%= link_to "注册", new_user_registration_path %></li>
            <% end %>
          </ul>

(7)修改下登录页面的样式

<div class="row">
  <div class="col-md-6">
    <%= form_for(resource, as: resource_name, url: session_path(resource_name)) do |f| %>
      <div class="form-group">
        <%= f.label :email, class: "control-label" %>
        <%= f.email_field :email, autofocus: true, class: "form-control" %>
      </div>

      <div class="form-group">
        <%= f.label :password, class: "control-label" %>
        <%= f.password_field :password, autocomplete: "off", class: "form-control" %>
      </div>

      <% if devise_mapping.rememberable? -%> 
        <div class="form-group">
          <%= f.check_box :remember_me %>
          <%= f.label :remember_me %>
        </div>
      <% end -%> 

      <div class="actions">
        <%= f.submit "登录", class: "btn btn-primary" %>
        <%= link_to "忘记密码", new_password_path(resource_name), class: "btn btn-link" %>
      </div>
    <% end %>
  </div>
</div>

(8)为了保护我们的方法,在每个方法前加一个登录校验app/controllers/application_controller.rb

class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery with: :exception

  before_action :authenticate_user!
end

(9)对于不需要登录就可以公开的一些页面,在controller里增加跳过验证的语句

class ProductsController < ApplicationController
  skip_before_action :authenticate_user!, only: [:index, :show]

 

 

<td><%= number_to_currency product.price, unit: "¥" %></td>

https://github.com/activerecord-hackery/ransack

添加Gemfile

gem 'ransack'

 

view中代码

          <%= form_tag products_path, method: :get, class: "navbar-form navbar-left" do %>
            <div class="form-group">
              <%= search_field_tag("q[name_cont]", params["q"] && params["q"]["name_cont"],
                                 class:"form-control input-sm search-form", placeholder: "输入商品名称")%>
            </div>
          <% end %>

controller里

  def index
    @q = Product.ransack(params[:q])
    @products = @q.result(distinct: true)
  end 

其中 name_cont会对name字段进行模糊查询

 

http://getbootstrap.com/css/#helper-classes-clearfix

清除浮动

div class="clearfix"

http://blog.csdn.net/shenlei19911210/article/details/48196441

 

在model里新建

  CHANNEL_TYPES = { 
    '信号源': :signal_source,
    '直播轮播': :live_and_rotate,
    '我的': :my_channel,
    'C 频道': :c_channel
  }

并增加方法

  def channel_type_human
    CHANNEL_TYPES.invert[channel_type.to_sym]
  end 

在view/form里可以直接用

      <div class="form-group">
        <%= f.label :channel_type,"频道类型", class: "col-sm-2 control-label" %>
        <div class="col-sm-2">
          <%= f.select :channel_type, options_for_select(LauncherChannel::CHANNEL_TYPES, @launcher_channel.channel_type),
            {}, class: "form-control" %>
        </div>
      </div>

之前没有加{}, 由于默认是四个参数的,最后一个才是html_option

select(method, choices = nil, options = {}, html_options = {}, &block)

Wraps ActionView::Helpers::FormOptionsHelper#select for form builders:

<%= form_for @post do |f| %>
  <%= f.select :person_id, Person.all.collect { |p| [ p.name, p.id ] }, include_blank: true %>
  <%= f.submit %>
<% end %>
Please refer to the documentation of the base helper for details.

Source: hide | on GitHub

# File actionview/lib/action_view/helpers/form_options_helper.rb, line 776
def select(method, choices = nil, options = {}, html_options = {}, &block)
  @template.select(@object_name, method, choices, objectify_options(options), @default_options.merge(html_options), &block)
end