1

I am using Ahoy Email to track emails I send to my restaurants. However I'dd like to create a relationship like so :

  • an AhoyMessage belongs_to a Restaurant

  • a Restaurant has_many AhoyMessages

so that I can access, for example:

ahoy_message.restaurant.phone_number
==> "+33612345678"

I know when I look at the docs that there is an easy way to do so with the User model, but I can only use my Restaurant model and hence the example in the doc does not work for my particular case.

Uj Corb
  • 1,959
  • 4
  • 29
  • 56

1 Answers1

1

The docs say it's polymorphic and you can use any model.

Try

class CouponMailer < ApplicationMailer
  track user: -> { Restaurant.find_by(email: message.to.first) }
end


class Restaurant < ApplicationRecord
  has_many :messages, class_name: "Ahoy::Message", as: :user
end

So you would still use ahoy_message.user.phone_number but the ahoy_message.user is a polymorphic association to a restaurant object.

SteveTurczyn
  • 36,057
  • 6
  • 41
  • 53
  • thank you very much @SteveTurczyn ! I actually thought about doing so but I was afraid there could be any conflict because I also have a `User` model. Are you sure there won't be any conflict ? – Uj Corb Jan 03 '19 at 18:00
  • 1
    Not according to the docs on the Ahoy Message readme. You could actually mix and match, so messages from one mailer the "user" would be "restaurant", and the messages from another mailer could be real users. – SteveTurczyn Jan 03 '19 at 18:02