Try using the query attribute of Ruby on Rails

Conclusion: You can use attribute name? Instead of blank? And present? (Some need to be careful)

Background: I wanted to add an array of integers (possibly nil)

Original my code ...

[Here is an array of Objects with hoge as the key].reject(|obj| !obj.hoge.nil?).sum(:hoge)

reject(|obj| !obj.hoge.nil?)In hoge removes nil's,sum(:hoge)I was going to add hoge with nil removed.

Modified version

[Here is an array of Objects with hoge as the key].select(&:hoge?).sum(:hoge)

reject(|obj| !obj.hoge.nil?)Butselect(&:hoge?)became. I tried to select the one that hoge? evaluates to true, this is what I learned this time. It is possible to express the attribute name?

Commentary

Similar article already exists My original code seems to have been bad code for Bad smell. (Reference page)

I also looked at Rails body code. This case statement seems to be the relevant part. To summarize the case statements, ...

First, true is true, false, nil is false.

when true        then true
when false, nil  then false

Next, it seems that it can be roughly divided into cases where the receiver has a specified attribute and cases where it does not.

if !type_for_attribute(attr_name) { false }
  if Numeric === value || !value.match?(/[^0-9]/)
    !value.to_i.zero?
  else
    return false if ActiveModel::Type::Boolean::FALSE_VALUES.include?(value)
    !value.blank?
  end
elsif value.respond_to?(:zero?)
  !value.zero?
else
  !value.blank?
end

! Type_for_attribute (attr_name) {false} will be true if the receiver does not have the corresponding attribute name. Moreover,Numeric === value || !value.match?(/[^0-9]/)in the case of(Numbers), 0 is false, otherwise it is true. If it is not a number, it will return false if it is false, and blank? If it is not.

Next is the case where the receiver has the corresponding attribute name. If value.respond_to? (: zero?) Has zero ?, ! Value.zero? is evaluated to be false when it is 0, otherwise it is true. If you don't have zero ?, the result of! Value.blank? Seems to be returned.

Summary

I thought it could be used in place of ʻattribute name.blank? And ʻattribute name.present? In many cases. One thing to keep in mind is that when it is 0, it becomes false. It was also mentioned in Reference article. What I wanted to do was simply add up, so it doesn't matter if 0 is played, but I wondered if it could be a problem in some cases.

Thank you for reading this far. Please point out any mistakes and we will correct them. (This article has nothing to do with the company)

Recommended Posts

Try using the query attribute of Ruby on Rails
[Ruby on Rails] Until the introduction of RSpec
[Ruby On Rails] How to search the contents of params using include?
Docker the development environment of Ruby on Rails project
[Ruby on Rails] Read try (: [],: key)
Basic knowledge of Ruby on Rails
[Rails] Register by attribute of the same model using Devise
(Ruby on Rails6) Display of the database that got the id of the database
Delete all the contents of the list page [Ruby on Rails]
A note about the seed function of Ruby on Rails
[Rails] Addition of Ruby On Rails comment function
Try using || instead of the ternary operator
[Ruby on Rails] Code check using Rubocop-airbnb
Try using the service on Android Oreo
Try using the Rails API (zip code)
Let's summarize "MVC" of Ruby on Rails
[Ruby on Rails] Change the save destination of gem refile * Note
Notes on using FCM with Ruby on Rails
[Ruby on Rails] Japanese notation of errors
Explanation of Ruby on rails for beginners ①
[Ruby on rails] Implementation of like function
Create a large number of records with one command using the Ruby on Rails seeds.rb file
How to create a query using variables in GraphQL [Using Ruby on Rails]
How to solve the local environment construction of Ruby on Rails (MAC)!
Implementation of Ruby on Rails login function (Session)
When the Ruby on Rails terminal rolls back
Recommendation of Service class in Ruby on Rails
Publish the app made with ruby on rails
Ruby on Rails ~ Basics of MVC and Router ~
[Ruby on Rails] A memorandum of layout templates
Determine the current page with Ruby on Rails
[Ruby on Rails] Individual display of error messages
Ruby on Rails Elementary
Ruby on Rails basics
Ruby On Rails Association
[Ruby on Rails] How to make the link destination part of the specified id
[Ruby on Rails] Solving the addiction when setting crontab using whenever in EC2
[Ruby on Rails] Implement a pie chart that specifies the percentage of colors
[Ruby on Rails] How to Japaneseize the error message of Form object (ActiveModel)
Ruby on Rails <2021> Implementation of simple login function (form_with)
[Ruby on Rails] Asynchronous communication of posting function, ajax
[Introduction] Try to create a Ruby on Rails application
[Ruby on Rails Tutorial] Error in the test in Chapter 3
Implementation of Ruby on Rails login function (devise edition)
[Ruby on Rails] How to change the column name
[Ruby on Rails] Implementation of tagging function/tag filtering function
[Ruby on Rails] Common processing between controllers (using concaves)
Solve the N + 1 problem with Ruby on Rails: acts-as-taggable-on
Rails6: Input the initial data of ActionText using seed
Ruby on Rails environment construction using VirtualBox, Vagrant, cyberduck
Explanation of Ruby on rails for beginners ⑥ ~ Creation of validation ~
Explanation of Ruby on rails for beginners ② ~ Creating links ~
(Ruby on Rails6) Reflecting the posted content from the form
Explanation of Ruby on rails for beginners ⑦ ~ Flash implementation ~
[Ruby on Rails] Implementation of validation that works only when the conditions are met
Ruby on rails learning record -2020.10.03
Portfolio creation Ruby on Rails
Try using view_component with rails
Ruby on rails learning record -2020.10.04
Try using Cocoa from Ruby
[Ruby on Rails] Debug (binding.pry)