fetch()函数

你可能还想在 new 动作中限制允许传入的属性。不过此时无法再根键上调用 require 方法,因为此时根键还不存在:

using fetch you can supply a default and use

the Strong Parameters API from there.

params.fetch(:blog, {}).permit(:title, :author)

fetch(key, *args)Link
Returns a parameter for the given key. If the key can’t be found, there are several options: With no other arguments, it will raise anActionController::ParameterMissing error; if more arguments are given, then that will be returned; if a block is given, then that will be run and its result returned.

params = ActionController::Parameters.new(person: { name: ‘Francesco’ })
params.fetch(:person) # => {“name”=>”Francesco”}
params.fetch(:none) # => ActionController::ParameterMissing: param not found: none
params.fetch(:none, ‘Francesco’) # => “Francesco”
params.fetch(:none) { ‘Francesco’ } # => “Francesco”

fetch(name, options = nil)Link
Fetches data from the cache, using the given key. If there is data in the cache with the given key, then that data is returned.

If there is no such data in the cache (a cache miss), then nil will be returned. However, if a block has been passed, that block will be passed the key and executed in the event of a cache miss. The return value of the block will be written to the cache under the given cache key, and that return value will be returned.

cache.write(‘today’, ‘Monday’)
cache.fetch(‘today’) # => “Monday”

cache.fetch(‘city’) # => nil
cache.fetch(‘city’) do
‘Duckburgh’
end
cache.fetch(‘city’) # => “Duckburgh”

fetch(key, *extras)Link
Same as Hash#fetch where the key passed as argument can be either a string or a symbol:

counters = ActiveSupport::HashWithIndifferentAccess.new
counters[:foo] = 1

counters.fetch(‘foo’) # => 1
counters.fetch(:bar, 0) # => 0
counters.fetch(:bar) { |key| 0 } # => 0
counters.fetch(:zoo) # => KeyError: key not found: “zoo”

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值