Mongoid_slug Rails 4更新/销毁对象 [英] Mongoid_slug Rails 4 update / destroy object

查看:73
本文介绍了Mongoid_slug Rails 4更新/销毁对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Rails应用程序中使用mongoig_slug gem.

I am using mongoig_slug gem in my rails app.

我可以使用适当的URL创建一个对象,但是我无法更新/删除该对象,并且控制台中没有错误消息. (我可以编辑包含正确数据的表单)

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)

我什至使用PRY来检入控制台,并且当我检查@book出口是否正确时,如果我执行@ book.destroy,它表示true,但不会销毁. 对于编辑,我还检查了@book,还检查了book_params.

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

推荐答案

您不能只复制该行slug_id_strategy: lambda {|id| id.start_with?('....')}而无需更改.您应该用定义ID是否为ID的点替换点.

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.

来自文档:

此选项应返回响应调用(可调用)并采用一个字符串参数的内容,例如一个lambda.如果字符串看起来像您的ID之一,则此callable必须返回true.

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.

因此,例如:

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

或:

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

或者可能是:

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

已更新

mongoid_slug的最新版本已过时,您应该使用github版本.因此,在您的Gemfile中:

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

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

还将field: _id行更改为:

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

原因_id类型不是字符串,并且发生此错误.这应该起作用.

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

这篇关于Mongoid_slug Rails 4更新/销毁对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆