In this post, slice function is used to get only necessary elements of params. What would be the function I should use to exclude an element of params (such as user_id)?
Article.new(params[:article].slice(:title, :body))
Thank you.
slice() is a method in Ruby that is used to return a sub-array of an array. It does this either by giving the index of the element or by providing the index position and the range of elements to return.
The first() is an inbuilt method in Ruby returns an array of first X elements. If X is not mentioned, it returns the first element only. Syntax: range1.first(X) Parameters: The function accepts X which is the number of elements from the beginning. Return Value: It returns an array of first X elements.
Use except:
a = {"foo" => 0, "bar" => 42, "baz" => 1024 } a.except("foo") # returns => {"bar" => 42, "baz" => 1024}
Inspired in the sourcecode of except in Rails' ActiveSupport
You can do the same without requiring 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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With