[Rails] Determine if a specific element exists in a hash or array [ActiveRecord] [has_attribute?]

A way to check if a particular element is present in a hash or array. If email is not registered, it will be registered, if it is registered, it will be a message.

Determine any hash

Take a hash like this as an example. Pay attention to nil ʻempty`.

@user = {
 "id" => 1,
 "name" => "Taro",
 "age" => 26,
 "from" => nil,
 "sex" => "",
 "created_at" => Sun, 21 Aug 2020 09:55:05,
 "updated_at" => Sun, 21 Aug 2020 09:55:05
}

Determined by has_attribute?

Determines if there is a particular element itself. You can get this result with has_attribute?.

@user.has_attribute?(:name) # => true
@user.has_attribute?(:from) # => true
@user.has_attribute?(:sex) # => true
@user.has_attribute?(:userid) # => false

A little confusing is that the result is true even if the content is nil ʻempty`. It means determining whether or not the element itself exists.

Determined by attribute_present?

Determines if the contents of a particular element are present. You can get this result with ʻattribute_present?`.

@user.attribute_present?(:name) # => true
@user.attribute_present?(:from) # => false
@user.attribute_present?(:sex) # => false
@user.attribute_present?(:userid) # =>error

Assuming the element exists, it determines if the contents are empty.

reference

There are many other methods that can be used with ActiveRecord, hashes, arrays, etc. https://api.rubyonrails.org/classes/ActiveRecord/AttributeMethods.html

Recommended Posts

[Rails] Determine if a specific element exists in a hash or array [ActiveRecord] [has_attribute?]
[Rails] How to load JavaScript in a specific view
Apply CSS to a specific View in Ruby on Rails