Search code examples
ruby-on-rails-4mongoidslug

Mongoid_slug Rails 4 update / destroy object


I am using mongoig_slug gem in my rails app.

I can create an object with the proper url but I can't update / delete the object and I have no error message in the console. (I can edit the form, which contains the correct data)

I even used PRY to check in the console and when I check @book exits and is correct, if I do @book.destroy it says true but does not destroy. For the edit, I also checked @book, I also checked book_params which is correct.

class Book
  include Mongoid::Document
  include Mongoid::Timestamps
  include Mongoid::Slug

  field :_id, type: String, slug_id_strategy: lambda {|id| id.start_with?('....')}

  field :name, type: String
  slug :name 
end

class BooksController < ApplicationController
   before_filter :get_book, only: [:show, :edit, :update, :destroy]

   def update
     if @book.update_attributes(book_params)
       redirect_to book_path(@book)
     else
       flash.now[:error] = "The profile was not saved, please try again."
       render :edit
     end
   end

   def destroy
     binding.pry
     @book.destroy
     redirect_to :back
   end

   def book_params
     params.require(:book).permit(:name)
   end

   def get_book
     @book = Book.find params[:id]
   end
end

Solution

  • You can't just copy that line slug_id_strategy: lambda {|id| id.start_with?('....')} without changes. You should replace dots with something that defines is it id or not.

    From docs:

    This option should return something that responds to call (a callable) and takes one string argument, e.g. a lambda. This callable must return true if the string looks like one of your ids.

    So, it could be, for example:

    slug_id_strategy: lambda { |id| id.start_with?('5000') } # ids quite long and start from the same digits for mongo.
    

    or:

    slug_id_strategy: lambda { |id| =~ /^[A-z\d]+$/ }
    

    or probably:

    slug_id_strategy: -> (id) { id =~ /^[[:alnum:]]+$/ }
    

    Updated

    The latest version of mongoid_slug is outdated, you should use github version. So in your Gemfile:

    gem 'mongoid_slug', github: 'digitalplaywright/mongoid-slug'
    

    Also change field: _id line to:

      field :_id, type: BSON::ObjectId, slug_id_strategy: lambda { |id| id =~ /^[[:alnum:]]+$/ }
    

    Cause _id type is not a string, and this occurs error. This should work.