如何使用friendly_id和history设置Rails多态模型

时间:2019-03-13 09:01:35

标签: ruby-on-rails polymorphic-associations friendly-id

我有一个Company和Seo模型(在Seo下面的链接中,称为PublicSlug),具有多语言关联,并且关心回答类似问题
Match multiple models in single Rails route with friendly_id

要引起关注,只要我添加:history选项,所有方法都可以使用。
当我在Rails控制台中更新Seo之后,出现错误

import { share } from 'rxjs/operators';
import { Observable } from "rxjs";

export abstract class CachcingServiceBase {
  protected cache<T>(getter: () => Observable<T>,
                     setter: (val: Observable<T>) => void,
                     retreive: () => Observable<T>): Observable<T> {
    const cached = getter();
    if (cached !== undefined) {
      return cached;
    } else {
      const val = retreive().pipe(share());
      setter(val);
      return val;
    }
  }

如何使用:history选项解析friendly_id中的模糊数据库列

models.seo.rb

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)

models / company.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 / concerns / sluggable.rb

class Company < ApplicationRecord
  include Sluggable

  belongs_to :city

end

1 个答案:

答案 0 :(得分:0)

更改多态的易记名称时,将解决数据库中的冲突歧义列。 Friendly_id还将sluggable_idsluggable_type用于历史记录。

class Seo < ApplicationRecord

  extend FriendlyId
  
  ... 
  belongs_to :sluggable, polymorphic: true
  #this line was problem
  

  ...

end