Search code examples
ruby-on-railsahoy

create a relationship between non User model and AhoyMessage


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.


Solution

  • 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.