The best way to find a unique entry in has_many through relationships

In my rails application, user can go to events -

user.rb

has_many :attendances
has_many :events, through: :attendances

event.rb

has_many :attendances
has_many :users, through: :attendances

... with an attendance table that consists of event_id, user_id and some other bits and parts -

attendance.rb

belongs_to :user
belongs_to :writers_event

When you are looking for specific traffic, I find myself using it. where .... first - for example,

attendance = Attendance.where(user_id: @user.id, event_id: this_event_id).first

And it seems to me that I missed the class in which we talked about using something like find_bythis in this type of situation - in other words, where you are sure that you are looking for something unique. It may not matter, but searching for a collection and then retrieving the first object from it seems wasteful and wrong.

Is there a better way?

, , ( ) . has_many ?

+4
3

find_by :

attendance = Attendance.find_by(user_id: @user.id, event_id: this_event_id)

.

:

current_user.attendances.find_by(event_id: this_event_id)
+3

:

attendance = Attendance.find_by(user_id: @user.id, event_id: this_event_id)

find_by, .

. find_by, , . ActiveRecord::RecordNotFound , , find_by!.

+5

Try the following:

Attendance.find_by_user_and_event(@user.id, this_event_id)

If the record is not found, it returns nil. If you want to create an exception

Attendance.find_by_user_and_event!(@user.id, this_event_id)
+2
source

Source: https://habr.com/ru/post/1616719/


All Articles