0

I'm using rails 7 and ruby 3.1.2.

My cookie I've created returns these keys and values:

>>  cookies[:utm_params]
=> "{:source=>\"facebook\", :medium=>\"facebook_feed\", :campaign=>\"123123123123\", :max_age=>2592000}"

And I've created these fields on my Subscription model:

#  utm_source             :string
#  utm_medium             :string
#  utm_campaign           :string

My Subscription.create code looks like this atm, but I can't figure out how to save them.

      @subscription = Subscription.create!({
        utm_source: cookies[:utm_params][:source],
        # utm_medium: cookies[:utm_params],
        # utm_campaign: cookies[:utm_params],
      })

EDIT: My own solution and refactor

application_controller.rb
UTM_COOKIE_NAME = "_ta_utm"

before_action :capture_utm_params

private

def capture_utm_params
  if(params.has_key?(:utm_medium))
    cookies[UTM_COOKIE_NAME] = { 
      expires: 30.days.from_now,
      value: {
        source: params[:utm_source],
        medium: params[:utm_medium],
        campaign: params[:utm_campaign]
      }.to_json
    }
  end
end

checkout_controller.rb
utm_tags = JSON.parse(cookies[UTM_COOKIE_NAME]) rescue nil
if utm_tags.present?
  source = utm_tags["source"]
  medium = utm_tags["medium"]
  campaign = utm_tags["campaign"]
end

@subscription = Subscription.create!({
  utm_source: source,
  utm_medium: medium,
  utm_campaign: campaign
})
  • The value in your cookie is a serialized Ruby hash which is not easily and safely parseable. Is it an option to serialize it in a different format? – spickermann Jul 23 '22 at 16:05

1 Answers1

0

You need to convert that string in to hash. I tried to use JSON.parse(string) on your string but it is not parsable as json. So i found this answer for you to convert that string into hash so that you can save the data you want. Hope it helps.

you can use the code in the answer i linked like this:

utm_hash = JSON.parse(cookies[:utm_params].gsub(/:([a-zA-z]+)/,'"\\1"').gsub('=>', ': ')).symbolize_keys
  • if you mean `cookies[:utm_params].to_json` then it will not change anything. the way utm_params set in the cookie is not easily parsable. i recommend store the utm_params data as JSON parsable format so that you can easliy parse with `JSON.parse(cookies[:utm_params])` or you can use the above code for your current string. – Mehmet Adil İstikbal Jul 23 '22 at 16:24
  • I got it working, edited my original post above :) – Emil Ståhl Myllyaho Jul 23 '22 at 16:37