在这个post中,slice函数用于仅获取params的必要元素。我应该使用什么函数来排除params元素(例如user_id)?
Article.new(params[:article].slice(:title, :body))
谢谢。
答案 0 :(得分:64)
使用except:
a = {"foo" => 0, "bar" => 42, "baz" => 1024 }
a.except("foo")
# returns => {"bar" => 42, "baz" => 1024}
答案 1 :(得分:1)
试试这个
params = { :title => "title", :other => "other", :body => "body" }
params.select {|k,v| [:title, :body].include? k } #=> {:title => "title", :body => "body"}
答案 2 :(得分:1)
灵感来自except in Rails' ActiveSupport
的源代码您可以执行相同操作而无需active_support/core_ext/hash/except
# h.slice( * h.keys - [k1, k2...] )
# Example:
h = { a: 1, b: 2, c: 3, d: 4 }
h.slice( * h.keys - [:b, :c] ) # => { a: 1, d: 4}
答案 3 :(得分:0)