保华的Rails学习笔记

暂未记住的知识点汇总

做了许多遍,有些知识点还是默写不出来,为了能让自己记住,就贴在这里,时不时的看一眼,时间长了,相信总是能熟练快速的写出来。
会一直更新内容,自己记住的,就删除,记不住的就先丢过来,继续前行,老师说要冲进度,其实非常有道理

1、bootstrap中关于alert的代码

app/views/common/_flashes.html.erb

<% if flash.any? %>
  <% user_facing_flashes.each do |key, value| %>
    <div class="alert alert-dismissable alert-<%= flash_class(key) %>">
      <button class="close" data-dismiss="alert">×</button>
      <%= value %>
    </div>
  <% end %>
<% end %>
app/helpers/flashes_helper.rb

module FlashesHelper
  FLASH_CLASSES = { alert: "danger", notice: "success", warning: "warning"}.freeze

  def flash_class(key)
    FLASH_CLASSES.fetch key.to_sym, key
  end

  def user_facing_flashes
    flash.to_hash.slice "alert", "notice","warning" 
  end
end

2、rake routes

有些verb还是没记住,例如patch是哪个action的,这些先背下来,总会用上的

3、db/seed.rb的写法

db/seed.rb
puts "這個種子檔會自動建立一個admin帳號, 並且創建 10 個 public jobs, 以及10個hidden jobs"

create_account = User.create([email: 'example@gmail.com', password: '12345678', password_confirmation: '12345678', is_admin: 'true'])
puts "Admin account created."

create_jos = for i in 1..10 do
  Job.create!([title: "Job no.#{i}", description: "這是用種子建立的第 #{i} 個Public工作", wage_upper_bound: rand(50..99)*100, wage_lower_bound: rand(10..49)*100, is_hidden: "false"])
end
puts "10 Public jobs created."

create_jos = for i in 1..10 do
  Job.create!([title: "Job no.#{i+10}", description: "這是用種子建立的第 #{i+10} 個Hidden工作", wage_upper_bound: rand(50..99)*100, wage_lower_bound: rand(10..49)*100,is_hidden: "true"])
end
puts "10 Hidden jobs created."

4、在做simple_form_for表单的时候,如果不想用表单的原始名称,可以用label,例如f.input :wage_lower_bound, :label: "薪资下限“

<h1>Edit a job</h1>
<%= simple_form_for [:admin,@job] do |f| %>
  <%= f.input :title %>
  <%= f.input :description %>
  <%= f.input :wage_lower_bound, :label => "薪资下限" %>
  <%= f.input :wage_upper_bound, label: "薪资上限" %>
  <%= f.input :contact_email %>
  <%= f.submit "Submit" %>
<% end %>

注意两种写法都是可以的

5、薪资大于0的正确写法

validates :wage_lower_bound, numericality: { greater_than: 0}

app/models/job.rb

  validates :wage_upper_bound, presence: true
  validates :wage_lower_bound, presence: true
  validates :wage_lower_bound, numericality: { greater_than: 0}

6、被隐藏的文章应该在首页看不到的正确写法

def index
    @jobs = Job.where(is_hidden: false)
  end

或者

def index
    @jobs = Job.where(:is_hidden => false)
  end

注意:这两种写法都可以,但是false不能加引号,一加引号就执行不正确

7、安装 FontAwesome

各种围标在:http://fontawesome.io/icons/
1)在gem挂上 gem 'font-awesome-rails'
2)执行bundle install
3)修改 app/assets/stylesheets/application.scss
加入*= require font-awesome
也加入@import "font-awesome";
4)重开rails server
5)helper改为

app/helpers/jobs_helper.rb
  def render_job_status(job)
    if job.is_hidden
      content_tag(:span, "", :class => "fa fa-lock")
    else
      content_tag(:span, "", :class => "fa fa-globe")
    end
  end

要改变图标,改变class中fa fa-后边的即可,例如 fa fa-map、fa fa-map-pin

8、加分题中的实作hide与public

1)在controller中写hide与public这两个action

def publish
    @job = Job.find(params[:id])
    @job.publish!
    redirect_to :back
  end
  def hide
    @job = Job.find(params[:id])
    @job.hide!
    redirect_to :back
  end

2)在model中写hide!和public!

app/models/job.rb
class Job < ApplicationRecord
  def publish!
    self.is_hidden = false
    self.save
  end

  def hide!
    self.is_hidden = true
    self.save
  end
end  

3)写routes.rb文件,把public与hide的path添加进去

config/routes.rb
  namespace :admin do
    resources :jobs do
      member do
        post :publish
        post :hide
      end
    end
  end

4)在index.html.erb中,在edit/delete后边添加public或者hide按钮

<% if job.is_hidden %>

    <%= link_to("Publish", publish_admin_job_path(job) , :method => :post, :class => "btn btn-xs btn-default") %>
  <% else %>
    <%= link_to("Hide", hide_admin_job_path(job), :method => :post,  :class => "btn btn-xs btn-default") %>
  <% end %>

9、下拉菜单的实现代码(前端)

<div class="dropdown clearfix pull-right">
    <button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenuDivider" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
      排序
        <span class="caret"></span>
    </button>
    <ul class="dropdown-menu" aria-labelledby="dropdownMenuDivider">
        <li>
          <%= link_to("按照薪资下限排序", jobs_path(:order => "by_lower_bound")) %>
        </li>
        <li>
            <%= link_to("按照薪资上限排序", jobs_path(:order => "by_upper_bound")) %>

        </li>
        <li>
          <%= link_to("按照发表时间排序", jobs_path ) %>

        </li>
    </ul>
</div>

结构分析:1)总体是一个div代码 2)div代码中有一个button代码与一个ul代码,3)ul代码中有3个li代码

10、carrierwave的应用

1)、在gem挂上carrierwave
(1)gem 'carrierwave'
(2)终端执行bundle install
(3)重开rails s
2)、在resume上增加字段attachment
(1)rails g migration add_attachment_to_resume
(2)新产生的文件内容

class AddAttachmentToResume < ActiveRecord::Migration[5.0]
  def change
    add_column :resumes, :attachment, :string
  end
end

(3)rake db:migrate
3)挂上 Attachment Uploader 到 Resume 上
carrierwave 使用的是“Uploader”这个机制,因此呢,我们要

rails g uploader attachment
然后再修改 model,挂上去

app/models/resume.rb
class Resume < ApplicationRecord
  belongs_to :user
  belongs_to :job

  mount_uploader :attachment, AttachmentUploader

  validates :content, presence: true
end

然后修改

app/views/resumes/new.html.erb
<%= simple_form_for [@job, @resume] do |f| %>
  <%= f.input :content %>
  <%= f.input :attachment %>

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

4)修改 resume_params

app/controllers/resumes_controller.rb
  def resume_params
    params.require(:resume).permit(:content, :attachment)
  end

11、添加搜索框

1)在index里边添加代码

def index
    jobs = Job.all
    if params[:search]
      @jobs = Job.published.search(params[:search])
    elsif
    @jobs = case params[:order]
            when 'by_lower_bound'
              Job.published.order('wage_lower_bound DESC')
            when 'by_upper_bound'
              Job.published.order('wage_upper_bound DESC')
            else
              Job.published.recent
            end
    end
  end

2)在model里边添加代码

  def self.search(search)
      where("title LIKE ? OR description LIKE ? ", "%#{search}%","%#{search}%")
  end

3)在view页面添加代码,这里添加到jobs首页

<%= form_tag(jobs_path, :method => "get", id: "search-form") do %>
<%= text_field_tag :search, params[:search], placeholder: "Search jobs" %>
<%= submit_tag "Search" %>
<% end %>

12 link_to do的用法

出自:http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html

<%= link_to(@profile) do %>
  <strong><%= @profile.name %></strong> -- <span>Check it out!</span>
<% end %>
# => <a href="/profiles/1">
       <strong>David</strong> -- <span>Check it out!</span>
     </a>

教材中的用法为:

<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>

link_to do的用法,虽然不是很懂,但是通过查资料,大概明白了它有用法,不理解的,还是先背下来怎么用吧,以后还会遇到的