Home > Blockchain >  Using & when referencing relationship in Rails
Using & when referencing relationship in Rails

Time:11-30

I am working through a tutorial book and I came across something I had never seen before. In rails I am accustomed to getting the values of a relationship like this

<%= current_user.favorites.count %>

The author of the book used the & operator when doing this though, which appeared to do the same thing (I believe that I understand the & operator, I have just never seen it used like this)

<%= current_user&.favorites&.count %>

There was no explanation for this, so I took it as just another way to write it, but I have never seen this before in years of working with Rails and reading books/tutorials.

Is there a performance reason for doing it like this, or is it just personal preference?

It was inside a turbo_frame_tag if that makes any difference.

CodePudding user response:

& is the safe navigation operator and prevents a NoMethodError if you call a non-existant method method (such as calling a method on Nil).

Its use here isn't really that strange - what you're calling an "association" is after really just a method generated what is presumably has_many :favorites. So here the author is calling the method no matter if the record exists or not and is then creating an extra db hit with a COUNT query. Not great.

Its all kind of silly too since you most like want to wrap it with some markup so you'll need an if anyways.

Using long chains of the safe navigation operator is regarded as an antipattern of sorts since it lets you violate the Law of Demeter with blatant disregard and masks bugs.

  • Related