looking for some solutions? You are welcome.

SOLVED: How to set Rails polymorphic model with friendly_id and history

Maximillian:

I have a Company and Seo Model (in link below Seo called PublicSlug) with polymophic association and concern similiar to answer
Match multiple models in single Rails route with friendly_id

to build concern and all works as long as I add :history option.
After when i update Seo in rails console I have a error

Traceback (most recent call last):
        3: from (irb):3
        2: from app/models/concerns/sluggable.rb:17:in `touch_seo'
        1: from app/models/seo.rb:28:in `update_slug'
ActiveRecord::StatementInvalid (Mysql2::Error: Column 'sluggable_id' in where clause is ambiguous: SELECT  1 AS one FROM `seos` INNER JOIN `friendly_id_slugs` ON `friendly_id_slugs`.`sluggable_id` = `seos`.`id` AND `friendly_id_slugs`.`sluggable_type` = 'Seo' WHERE `seos`.`id` != 10 AND (sluggable_id <> 10) AND `seos`.`slug` = 'san-fransisco2' LIMIT 1)

How to resolve ambigous database column in friendly_id using :history option

models.seo.rb

class Seo < ApplicationRecord

  extend FriendlyId
  
  friendly_id :set_candidates, use: [:slugged, :history ] 
  belongs_to :sluggable, polymorphic: true
  validates :slug, presence: true, uniqueness: { case_sensitive: false }


  def should_generate_new_friendly_id?
    true
    #always 
  end

  def update_slug
    self.should_generate_new_friendly_id?
    self.save!
  end

  private
  def set_candidates
    case sluggable_type
    when 'Company' then company_candidates
    when 'City' then city_candidates
    end
  end

  def company_candidates
    [ 
      sluggable.name,
      ["#{sluggable.name} w mieście #{sluggable.city.name} na ulicy #{sluggable.street}"]
    ]
  end

  def city_candidates
    [ sluggable.name ]
  end


end

models/company.rb

class Company < ApplicationRecord
  include Sluggable

  belongs_to :city

end

models/concerns/sluggable.rb

module Sluggable
  extend ActiveSupport::Concern

  included do
    before_validation :create_seo
    has_one :seo, dependent: :destroy, as: :sluggable
    after_update :touch_seo
    #delegate :slug, to: :seo, prefix: :setting
    #line above is unnecessary

    private
      def create_seo
        self.seo = Seo.new unless seo.present?
      end

      def touch_seo
        self.seo.update_slug
      end
  end
end



Posted in S.E.F
via StackOverflow & StackExchange Atomic Web Robots
Share:

No comments:

Recent