2018年1月30日 星期二
Ruby Array(params[:ids])
关于 Array(params[:ids] 这个用法,如果是 Array([1,2,3]) 会等同于 [1,2,3] 没变,但是 Array[nil] 会变成 [] 空数组,这可以让 .each 方法不会因为 nil.each 而爆错。如果不这样处理,在没有勾选任何 offer 就送出的情况,就会爆出 NoMethodError 错误。除非你额外检查 params[:id] 如果是 nil 就返回,但不如用 Array 来的精巧。
来自 ihower 大大在全栈营教材中的 Pro tips
原來 rails5 以後 ActiveRecord_Collection 可以接收 update 了
原來 rails5 以後 ActiveRecord_Collection 可以接收 update 了
ex:
```rb
User.where(is_active: true).update(is_active: false)
```
https://blog.bigbinary.com/2016/06/10/rails-5-allows-updating-relation-objects-along-with-callbacks-and-validations.html
ex:
```rb
User.where(is_active: true).update(is_active: false)
```
https://blog.bigbinary.com/2016/06/10/rails-5-allows-updating-relation-objects-along-with-callbacks-and-validations.html
2018年1月22日 星期一
為什麼 ruby constant 要 freeze
因為 ruby 不會釋放 constant 的 memory,所以要 freeze,例如
```rb
class Test
HELLO = "World".freeze
end
```
這樣就不會一直重複建立 memory,而只會建立一次
https://www.sitepoint.com/ruby-uses-memory/
```rb
class Test
HELLO = "World".freeze
end
```
這樣就不會一直重複建立 memory,而只會建立一次
https://www.sitepoint.com/ruby-uses-memory/
2018年1月4日 星期四
rails csrf token
關於什麼是 CSRF: https://everyday1percent.blogspot.com/2017/12/csrf.html
rails 主要就是這裡
```
def csrf_meta_tags
if protect_against_forgery?
[
tag("meta", name: "csrf-param", content: request_forgery_protection_token),
tag("meta", name: "csrf-token", content: form_authenticity_token)
].join("\n").html_safe
end
end
```
所以前端要用的話就要在 Header 送 X-CSRF-Token 這個參數
https://stephenhowells.net/rails-5-user-registration-with-devise-vue-js-and-axios/
這裡有簡單的用法(前端使用 Axois)
後來搭配 gon 實作成:
```js
import axios from 'axios'
const create = (baseURL = 'http://localhost:3000/') => {
const api = axios.create({
// baseURL,
headers: {
'Cache-Control': 'no-cache',
'X-Requested-With': 'XMLHttpRequest',
'X-CSRF-Token': gon.general.rails.csrf.token
},
timeout: 10000
})
const cancel = ({ market, id }) => api.delete(`/exchange/markets/${market}/orders/${id}`)
return {
cancel
}
}
export default {
create
}
```
https://medium.com/rubyinside/a-deep-dive-into-csrf-protection-in-rails-19fa0a42c0ef
rails 主要就是這裡
```
def csrf_meta_tags
if protect_against_forgery?
[
tag("meta", name: "csrf-param", content: request_forgery_protection_token),
tag("meta", name: "csrf-token", content: form_authenticity_token)
].join("\n").html_safe
end
end
```
所以前端要用的話就要在 Header 送 X-CSRF-Token 這個參數
https://stephenhowells.net/rails-5-user-registration-with-devise-vue-js-and-axios/
這裡有簡單的用法(前端使用 Axois)
後來搭配 gon 實作成:
```js
import axios from 'axios'
const create = (baseURL = 'http://localhost:3000/') => {
const api = axios.create({
// baseURL,
headers: {
'Cache-Control': 'no-cache',
'X-Requested-With': 'XMLHttpRequest',
'X-CSRF-Token': gon.general.rails.csrf.token
},
timeout: 10000
})
const cancel = ({ market, id }) => api.delete(`/exchange/markets/${market}/orders/${id}`)
return {
cancel
}
}
export default {
create
}
https://medium.com/rubyinside/a-deep-dive-into-csrf-protection-in-rails-19fa0a42c0ef
訂閱:
文章 (Atom)
