Rails中常用的gem

Devise

Devise 是一個(gè) Rails 熱門(mén)的 gem, 專(zhuān)門(mén)用來(lái)做“用戶(hù)登錄系統(tǒng)”

Gemfile文件添加

gem 'devise'

安裝

bundle install

產(chǎn)生用戶(hù)登錄系統(tǒng)的必要文件

rails g devise:install
rails g devise user
rails db:migrate
rails g devise:views

一個(gè)用戶(hù)登錄系統(tǒng)產(chǎn)生了

主要用在某些action前進(jìn)行是否已登錄的驗(yàn)證

before_action :authenticate_user! , only: [:xxx] #xxx代表某些action

分頁(yè)

will_paginate

Gemfile文件添加

gem 'will_paginate'

安裝

bundle install

用法

paginate(:page => params[:page], :per_page => 5) 在某個(gè)action下使用,如:

@posts = @posts.paginate(:page => params[:page], :per_page => 5)

然后在視圖中渲染

<%= will_paginate @posts %>

bootstrap樣式的will_paginate

will_paginate-bootstrap

Gemfile文件添加

gem 'will_paginate-bootstrap'

安裝

bundle install

paginate(:page => params[:page], :per_page => 5) 在某個(gè)action下使用,如:

@posts = @posts.paginate(:page => params[:page], :per_page => 5)

然后在視圖中渲染

<%= will_paginate @posts, renderer: BootstrapPagination::Rails %>

simple_form--讓表單寫(xiě)法更簡(jiǎn)單

Gemfile文件添加

gem 'simple_form'

安裝

bundle install

安裝 simple_form for bootstrap 的設(shè)定

rails generate simple_form:install --bootstrap

在視圖中使用

<%= simple_form_for @group do |f| %>
  <div class="form-group">
    <%= f.input :title, input_html: { class: "form-control"} %>
    <%= f.input :description, input_html: { class: "form-control"} %>
  </div>
  <%= f.submit "Submit", class: "btn btn-primary", data: { disable_with: "Submiting..." } %>
<% end %>

字體圖標(biāo)

Gemfile文件添加

gem 'font-awesome-rails'

安裝

bundle install

application.scss中添加

*= require font-awesome

@import "font-awesome";

在視圖中使用

<%= link_to(content_tag(:i, '登出', class: 'fa fa-sign-out'), destroy_user_session_path, method: :delete) %> 

上傳文檔

Gemfile文件添加

gem 'carrierwave'

安裝

bundle install

添加字段

rails g migration add_attachment_to_your_model_name(復(fù)數(shù)形式)

在最新的遷移文件添加字段

class AddAttachmentToResume < ActiveRecord::Migration[5.0]
  def change
    add_column :your_model_name(復(fù)數(shù)形式), :attachment, :string 
  end
end

運(yùn)行遷移

rails db:migrate

生成上傳文件的uploader

rails g uploader attachment

在your_model掛載

class YourModelName < ApplicationRecord

  mount_uploader :attachment, AttachmentUploader

  validates :content, presence: true
end

在視圖使用

<%= simple_form_for [@job, @resume] do |f| %>
  <%= f.input :content %>
  <%= f.input :attachment %>

  <%= f.submit "送出" %>
<% end %>

在.gitignore文件忽略public/uploads文件

public/uploads

model注解--annotate(版本變化可能導(dǎo)致命令錯(cuò)誤,請(qǐng)以github穩(wěn)準(zhǔn))

安裝

gem 'annotate'

安裝

bundle install

生成注解

annotate --exclude tests,fixtures,factories,serializers

圖片上傳

安裝系統(tǒng)支持包

sudo  apt-get install imagemagick

Gemfile文件添加

gem 'carrierwave'

gem 'mini_magick'

安裝

bundle install

生成image uploader

rails g uploader image

生成migration

rails g migration add_image_to_your_model

添加字段

add_column :your_models, :image, :string

運(yùn)行遷移

rake db:migrate

掛載

class your_model  < ApplicationRecord
 mount_uploader :image, ImageUploader
end

圖片上傳設(shè)置

class ImageUploader < CarrierWave::Uploader::Base

  # Include RMagick or MiniMagick support:

  # include CarrierWave::RMagick

  include CarrierWave::MiniMagick

  # Choose what kind of storage to use for this uploader:

  storage :file
  # storage :fog


  # Override the directory where uploaded files will be stored.

  # This is a sensible default for uploaders that are meant to be mounted:

  def store_dir
    "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
  end

  process resize_to_fit: [800, 800]

  version :thumb do
    process resize_to_fill: [200,200]
  end

  version :medium do
    process resize_to_fill: [400,400]
  end

在your_controller設(shè)置白名單

def product_params
 params.require(:product).permit(:title, :description, :quantity, :price, :image)
end

在視圖使用

 <div class="group">
    <%= f.input :price %>
  </div>

  <% if @product.image.present? %>
    <span>目前商品圖</span> <br>
    <%= image_tag(@product.image.thumb.url) %>
  <% end %>

  <div class="group">
    <%= f.input :image, as: :file %>
  </div>

在.gitignore忽略上傳的文件

public/uploads

顯示圖片

<div class="row">
  <% @products.each do |product| %>
    <div class="col-xs-6 col-md-3">
      <%= link_to product_path(product) do %>
        <% if product.image.present? %>
          <%= image_tag(product.image.thumb.url, class: "thumbnail") %>
        <% else %>
          <%= image_tag("http://placehold.it/200x200&text=No Pic", class: "thumbnail") %>
        <% end %>
      <% end %>
      <%= product.title %> ¥ <%= product.price %>
    </div>
  <% end %>
</div>   

Debug神器

Gemfile添加

group :development do
  gem 'pry'
  gem 'awesome_rails_console'
end

安裝

bundle install

在需要的地方

binding.pry  # 控制器使用
<% binding.pry %> # 視圖使用

后臺(tái)調(diào)整排序的功能

Gemfile添加

gem 'acts_as_list'  # https://github.com/brendon/acts_as_list/tree/v0.9.13

安裝

bundle install

生成migration

rails g migration AddPositionToYourModel position:integer

添加字段

class AddPositionToPost < ActiveRecord::Migration[5.2]
  def change
    add_column :posts, :position, :integer
    Post.order(:updated_at).each.with_index(1) do |post, index|
      post.update_column :position, index
    end
  end
end

運(yùn)行遷移

rails db:migrate

在your_model

class Post < ApplicationRecord
    acts_as_list
end

在控制器使用

@post = Post.find(params[:id)

@post.move_lower  # 向上上移一位
@post.move_higher # 向下移一位
@post.move_to_top # 置頂
@post.move_to_bottom # 置底

使用position字段排序

@posts = Post.all.order("position ASC)

有限狀態(tài)機(jī)(用于訂單狀態(tài)的更改)

Gemfile文件添加

gem 'aasm' # 參考網(wǎng)站 https://fullstack.qzy.camp/posts/698

安裝

bundle install

生成migration

rails g migration add_aasm_state_to_order

添加字段

class AddAasmStateToOrder < ActiveRecord::Migration
  def change
    add_column :orders, :aasm_state, :string, default: "order_placed"
    add_index  :orders, :aasm_state
  end
end

your_model添加AASM

class Order < ApplicationRecord

  include AASM

  aasm do
    state :order_placed, initial: true
    state :paid
    state :shipping
    state :shipped
    state :order_cancelled
    state :good_returned


     event :make_payment, after_commit: :pay! do
       transitions from: :order_placed, to: :paid
     end

    event :ship do
      transitions from: :paid,         to: :shipping
    end

    event :deliver do
      transitions from: :shipping,     to: :shipped
    end

    event :return_good do
      transitions from: :shipped,      to: :good_returned
    end

    event :cancel_order do
      transitions from: [:order_placed, :paid], to: :order_cancelled
    end
  end

end

在控制器使用

@order = Order.find(params[:id)

@order.make_payment!
@orde.ship!
@order.deliver!


最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀(guān)點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容