User editable slugs with Friendly ID

不羁的心 提交于 2019-12-05 06:52:12

This is how i solved it:

class Station < ActiveRecord::Base
  extend FriendlyId
  belongs_to :user
  has_many  :measures
  validates_uniqueness_of :hw_id
  validates_presence_of :hw_id
  class_attribute :zone_class
  self.zone_class ||= Timezone::Zone
  friendly_id :name, :use => [:slugged, :history]
  before_save :evaluate_slug
  before_save :set_timezone!


  def should_generate_new_friendly_id?
    if !slug?
      name_changed?
    else
      false
    end
  end

end

And the tests:

/spec/models/station_spec.rb

describe Station do
  ...   
  let(:station) { create(:station) }

  describe "slugging" do
    it "should slug name in absence of a slug" do
      station = create(:station, name: 'foo')
      expect(station.slug).to eq 'foo'
    end

    it "should use slug if provided" do
      station = create(:station, name: 'foo', slug: 'bar')
      expect(station.slug).to eq 'bar'
    end
  end
  ...
end

/spec/controllers/stations_controller.rb

describe StationsController do

    ...

    describe "POST create" do
        it "creates a station with a custom slug" do
          valid_attributes[:slug] = 'custom_slug'
          post :create, {:station => valid_attributes}
          get :show, id: 'custom_slug'
          expect(response).to be_success
        end

        ...
    end

    describe "PUT update" do
        it "updates the slug" do
          put :update, {:id => station.to_param, :station => { slug: 'custom_slug' }}
          get :show, id: 'custom_slug'
          expect(response).to be_success
        end

        ...
    end 

    ...
end

To change what parameter is used as the slug you just need to change the friendly_id parameter:

class Station < ActiveRecord::Base
  extend FriendlyId
  belongs_to :user
  has_many  :measures
  validates_uniqueness_of :hw_id
  validates_presence_of :hw_id
  class_attribute :zone_class
  self.zone_class ||= Timezone::Zone
  friendly_id :SLUGNAME, :use => [:slugged, :history]

  before_save :set_timezone!

  ....

  def should_generate_new_friendly_id?
   name_changed? or SLUGNAME_changed?
  end
end

Then in your view just have a way for the user to alter the slugname, following your view:

<%=
   f.div_field_with_label(:SLUGNAME) do |key|
     f.text_field(key)
   end
%>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!