In my rails app, a user can go along 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 which is made up of event_id, user_id and some other bits and pieces -
attendance.rb
belongs_to :user
belongs_to :writers_event
When looking for a particular attendance I find myself using .where ... .first - e.g.
attendance = Attendance.where(user_id: @user.id, event_id: this_event_id).first
And it strikes me that I missed the class where we talked about using something like find_by
in this type of situation - in other words, where you are confident that you are looking for something unique. It might not matter, but searching for a collection then taking the first object from it feels wasteful and wrong.
Is there a better way?
I had a look around, and this was closest, but does not (I don't think) really cover it. How to display unique records from a has_many through relationship?