这里有我的脚丫印😄

程序媛


  • 首页

  • 归档

delete_all vs destroy_all

发表于 2016-08-13 |

delete (删除某一个或多个以id为条件的记录)
Article.delete(4) (会返回影响记录条数,如1)
Article.delete([5, 6]) (会返回影响记录条数,如0)

delete_all (删除带条件的记录)
Article.delete_all(“published_at < ‘2011-01-01’”) (也会返回影响记录条数)

destroy (没有返回值)
Article.destroy(1)
Article.destroy([2,3])

a = Article.first
a.destroy 实例级别方法

Article.destory_all("published_at < '2011-01-01'") (删除带条件的记录)

类级别方法

Rails 会调用每个子对象的 destroy 方法,再调用父对象的 destroy 方法。会触发 model 中定义的回调(before_remove, after_remove , before_destroy 和 after_destroy)
delete方法绕过了一些Active Record的回调(callback)和验证函数,而使用destory则不会,通常我们使用destory方法来确保我们的数据库是一致的,并且不会破坏Model中所包含的业务逻辑。

在被移除之前,“dependent destroy” 会选择所有受限记录,建立其对象,并调用各自的毁灭方法。此方法允许你移除所有受限数据。但是,当涉及大量数据时,这种方法就不管用了。
至于 “dependent delete_all”,它会通过一条 SQL 查询移除自己。它效率很高,但是,在这种情况下,你得自己考虑数据库的完整性。

scope的用法

发表于 2016-08-07 |

scope可以将查询条件整合起来,让程序简洁易懂。并且可以串接使用。

1
2
3
4
5
6
7
8
class Event < ActiveRecord::Base
scope :open_public, -> { where( :is_public => true ) }
scope :recent_three_days, -> { where(["created_at > ? ", Time.now - 3.days ]) }
end
调用
Event.open_public
Event.open_public.recent_three_days

预设的scope

1
2
3
class Event < ActiveRecord::Base
default_scope -> { order('id DESC') }
end

暂时取消预设的scope

1
2
3
4
Event.unscoped do
Event.all
# SELECT * FROM events
end

1
2
3
4
5
6
7
8
class Event < ActiveRecord::Base
scope :recent, ->(date) { where("created_at > ?", date) }
# 等同於 scope :recent, lambda{ |date| where(["created_at > ? ", date ]) }
# 或 scope :recent, Proc.new{ |t| where(["created_at > ? ", t ]) }
end
Event.recent( Time.now - 7.days )

render在controller中的用法

发表于 2016-08-07 |

1.相应浏览器
render :nothing => true 空响应到浏览器
render :edit (或render :action => “edit”) 响应edit action,从而返回edit.html.erb页面
render ‘products/show’ (或render :template => ‘products/show’) 响应另一个controller中的action
render “/u/apps/warehouse_app/current/app/views/products/show” (或render :file =>
“/u/apps/warehouse_app/current/app/views/products/show”) 响应application以外的views
render :inline =>
“<% products.each do |p| %>

<%= p.name %>

<% end %>” 没有对应页面的,响应内容给浏览器
render :inline =>
“xml.p {‘Horrid coding practice!’}”, :type => :builder

render :update do |page|
page.replace_html ‘warning’, “Invalid options supplied”
end

render :text => “OK”
render :json => @product
render :xml => @product
render :js => “alert(‘Hello Rails’);”
render :file => filename, :content_type => ‘application/rss’
render :layout => ‘special_layout’
render :layout => false
render :status => 500
render :status => :forbidden
render :xml => photo, :location => photo_url(photo)

jdstore

发表于 2016-08-03 |

1.fork 项目
步骤:
fork进入自己的git,然后

git clone git@github.com:XXXXX/job-listing.git (clone 到本地)
cd job-listing
cp config/database.yml.example config/database.yml (复制 database.yml.example)
bundle check ; bundle install (检查gem,安装gem)
git checkout -b version-1 (git checkout version-1)
rails s (跑起來)

(新建专案)
rm -rf suggestotron
rails new suggestotron
cd suggestotron
git init
git status
git add . (git add foo.txt 把名叫 foo.txt 的檔案加進追蹤修訂。
git add . (“git add dot”) 把所有新檔案和改過的檔案加進追蹤修訂,但「保留」你刪掉的檔案。
git add -A 全部加進追蹤修訂,包括刪掉的檔案。)
git commit -m “Added all the things”
-m “Added all the things 這個捷徑讓你可以直接寫下 commit message。你可以省略之,這樣子 git 會打開一個編輯器請你填寫詳細的 commit message。
rails generate scaffold topic title:string description:text
rake db:migrate
rails server
generate scaffold 告訴 Rails 去建立一堆檔案讓 topics 可以動。
topic 是告訴 rails 新的 Model 的名字是什麼。
title:string 是說 topics 有標題(title),它是一個字串(String)。
description:text 是說 topics 有內文(description),它是一段文字(Text)。(「字串」跟「文字」的差別?基本上「文字」是用來儲存可能會很長的字串。)

2.套上bootstrap
gem “bootstrap-sass”
bundle install (注意:修改完 Gemfile 都要執行 bundle install)
mv app/assets/stylesheets/application.css app/assets/stylesheets/application.scss
(將 application.css 更名為 application.scss)
application.scss中
@import “bootstrap-sprockets”;
@import “bootstrap”;

mkdir app/views/common
touch app/views/common/_navbar.html.erb
touch app/views/common/_footer.html.erb
修改全域 HTML 樣式 application.html.erb引入nav和footer

rails g controller welcome
touch app/views/welcome/index.html.erb
config/routes.rb
root ‘welcome#index’

app/assets/javascripts/application.js
  //= require bootstrap/alert

touch app/views/common/_flashes.html.erb
<% if flash.any? %>
<% user_facing_flashes.each do |key, value| %>



<%= value %>

<% end %>
<% end %>

touch 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

<%= render “common/flashes” %>

3.安装登入系统
gem “devise”
bundle install
rails g devise:install
rails g devise user
rake db:migrate

4.安装SimpleForm
gem “simple_form”
bundle install
rails generate simple_form:install –bootstrap
安裝 simple_form for bootstrap 的設定
這個指令會產生兩個檔案
config/initializers/simple_form.rb
config/initializers/simple_form_bootstrap.rb (這個是 Bootstrap 表單的「佈景」

5.rails g controller admin::products
rails g model product title:string description:text quantity:integer price:float
rake db:migrate

去做CRUD

6.增加is_admin
rails g migration add_is_admin_to_user
add_column :users, :is_admin, :boolean, default: false
rake db:migrate
def admin?
is_admin
end

7.上传压缩图
gem “carrierwave”
gem “mini_magick”
bundle install

rails g migration add_image_to_product
add_column :products,:image,:string
rake db:migrate
rails g uploader ImageUploader

在uploader中
include CarrierWave::MiniMagick
rocess 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

在Product中
mount_uploader :image,ImageUploader

在rails console中删除表
ActiveRecord::Migration.drop_table(:table_name)

form_for

发表于 2016-08-02 |

1.
<% form_tag(‘/jobs’), method: “get” %>
<%= text_field_tag ‘queryString’ %>
<% end %>
这一段可以提交queryString到jobs#index中。使用params[:queryString]就能得到传递的参数值。

2.提交额外的参数到后台
主要看form
如果是simple_form_for @product像這樣的话你里面的input就必须放model有的栏位
但是如果是simple_form_for “” , url:products_path 像这样直接指定要request url的話f.input就看你 要填什么,而不需要和model中的栏位一致
用text_field_tag是在你的simple form有用到model但是又想要送model沒有的栏位过去时用的一种方 法。
text_field_tag传递到后台的是不需要写入strong parameters。如果要写入数据库的话,则必须加入到strong parameters

  1. <% form_for @post do |f| %>
    如果form_for后面需要指定url的话,使用
    <% form_for,url:post_path,method: :post do |f| %>

4.呃,去google guide rails ,搜索文档

5.我自己用表单提交到index遇到的问题

<%= form_tag(‘/jobs’,id: :form ,method: “get”) do %>
<%= select_tag “order”,raw(‘ ‘),class: “custom-select” %>

<%= submit_tag(value = “search”, class: “btn btn-primary”) %>
<% end %>

这个form会提交到,jobs#index中。

但是如果把method: “get”改成method: “post”,就会报错
原因:form指向的action是/jobs并且是post提交的话,rails会解析成jobs#create,这样的话,就进入了我们不该进入的action,从而会保错。

解决方法:
1.就不要改成post;因为这里是做查询,不会对数据做修改等不安全操作,所以,可以不要改成post。
2.可以重新写一个action,比如jobs#serach,把post表单提交的action指向jobs#search
3.在routes中加入post ‘/jobs’ => ‘jobs#index’,明确指定了/jobs的路径所对应的action,这样就不会被默认解析到jobs#create

6.参考别人的排序
排序:
<%= simple_form_for “” , url:products_path , method: :get , remote:true , html:{class:”form-inline order-by”, id: ‘sort_form’} do |f| %>
<%= f.input :sort , label:”Sort by : “ , as: :select , collection:Product.order_condition , required:false , include_blank: false , input_html:{id:”sort_submit”} %>
<% end %>

def self.order_condition
[“Default”,”New”, “Sale”,”Price: low to high”,”Price: high to low”]
end

Ruby

发表于 2016-07-30 |

阅读link_to的文档:
1.Look in the source
git clone http://github.com/rails/rails.git
cd rails
grep -rin ‘def link_to’
2.Look at api.rubyonrails.org
搜索link_to
3.dash中搜索

CSS自学

发表于 2016-07-25 |

1.margin 与 padding 的差异
margin:外边距
围绕在元素边框的空白区域是外边距。设置外边距会在元素外创建额外的“空白”。
padding:内边距
CSS padding 属性定义元素边框与元素内容之间的空白区域。

2.什麼是 box model
CSS 框模型
规定了元素框处理元素内容、内边距、边框 和 外边距 的方式。

3.為何要使用 em 而非 px 來定義字的大小
em:在 CSS 中,em 是非常有用的单位,因为它可以自动适应用户所使用的字体。
px:像素 (计算机屏幕上的一个点)

  1. h1 {margin : 10px 0px 15px 5px;}
    margin-top: 10px
    margin-right: 0px
    margin-left: 15px
    margin-bottom 15px

HTML自学

发表于 2016-07-25 |

1.div和span的不同:
标签 描述

定义文档中的分区或节(division/section)。
它属于块级元素,浏览器会在其前后显示折行
如果与 CSS 一同使用,
元素可用于对大的内容块设置样式属性。

<span>    定义 span,用来组合文档中的行内元素。
                是内联元素,可用作文本的容器
        当与 CSS 一同使用时,<span> 元素可用于为部分文本设置样式属性

2.class 与 id 的不同
class:classname 规定元素的类名(classname) 类选择器(标签可以共用)
id:id 规定元素的唯一 id id选择器(一个标签职能一个id)

3.p 与 br 的不同
p 段落, 浏览器会自动地在段落的前后添加空行。(p是块级元素)
br 换行, 元素是一个空的 HTML 元素。由于关闭标签没有任何意义,因此它没有结束标签。

4.如何使用 table 排版
使用table和css共同协作排版。

Heroku

发表于 2016-07-25 |

网站部署空间
利用git 上传部署
git push heroku master
优势:部署快速
还有:AWS 或 Linode 或 青云

heroku restart -a jdstore 重启 heroku 项目。

heroku create –a jdstore 创建特定名称的项目。

heroku config 查看配置参数。

StudyResource

发表于 2016-07-19 |

git:
官网:https://github.com/chenyunli6
学习参考:https://backlogtool.com/git-guide/tw/
http://www.bootcss.com/p/git-guide/

routes:
学习参考:http://kuro-sean-blog.logdown.com/posts/638977

ruby:
https://ihower.tw/rails4/restful.html
https://ihower.tw/rails4/activerecord-query.html

Bootstrap 的官網網址在:http://getbootstrap.com/
Bootstrap 的 template 要去哪裡下載?
https://getbootstrap.com/examples/navbar/

其實 Rails 還有很多內建驗質函式,你可以看這裡:http://guides.rubyonrails.org/active_record_validations.html

各种功能的gem 一览 :https://www.ruby-toolbox.com/
https://railscasts.com

.gitignore
可以设定哪些档案不被git存取
比如说config/database.yml

你不知道怎樣寫效果 可以到這裡看人家怎麼搭配的
http://bootsnipp.com/

工具
http://railscasts.com/

教材
https://www.gitbook.com/book/rocodev/rails-102/details

老师写的网站:http://www.66kjobs.tw/ 源码:https://github.com/xdite/66kjobs

1…789

陈云莉 m18301662790@gmail.com

记录一些技术点,留下一些生活感悟

82 日志
25 标签
© 2017 陈云莉 m18301662790@gmail.com
由 Hexo 强力驱动
|
主题 — NexT.Gemini v5.1.3