mercredi 8 juin 2016

Trouble accessing attributes of associated read only model

I'm using the friendly_id gem to generate slugs.

I have a model like this

class Veterinarian < ApplicationRecord
  extend FriendlyId

  belongs_to :user
  has_one :profile, through: :user

  friendly_id :slug_string, use: :slugged

  def slug_string
    "#{profile.first_name} #{profile.last_name} #{profile.city}"
  end
end

And another model like this.

class Profile < ApplicationRecord
  include ReadOnlyModel

  belongs_to :user
end

ReadOnlyModel looks like this

module ReadOnlyModel
  extend ActiveSupport::Concern

  included do
    attr_readonly(*column_names)
  end

  def readonly?
    true
  end

  def destroy
    raise ActiveRecord::ReadOnlyRecord
  end

  def delete
    raise ActiveRecord::ReadOnlyRecord
  end
end

My issue comes when I'm trying to access profile attributes inside of the veterinarian model. profile.first_name, profile.last_name, etc.

When friendly_id tries to update the slug, it throws an error telling me that the profile model is read only, however I'm just accessing an attribute and using it to create a string for friendly_id to use, nothing is changing in the profile model. However I can do Veterinarian.last.slug_string in the console and it outputs correctly with no errors.

I've been scratching my head for a good hour and haven't been able to figure out what's going on. It's probably something simple that I'm overlooking. Any help would be appreciated.

Aucun commentaire:

Enregistrer un commentaire