【问题标题】:Mongoid_slug Rails 4 update / destroy objectMongoid_slug Rails 4 更新/销毁对象
【发布时间】:2014-08-07 16:45:58
【问题描述】:

我在我的 Rails 应用程序中使用 mongoig_slug gem。

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

我什至使用 PRY 来检查控制台,当我检查 @book 退出并且是否正确时,如果我执行 @book.destroy,它会显示为 true,但不会破坏。 对于编辑,我还检查了@book,我还检查了正确的 book_params。

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

【问题讨论】:

  • @startup.destroy,不是@book.destroy,所以你不要毁了这本书。
  • 这只是一个错字,因为我在 2 个不同的项目中,但我的代码是 @book.destroy
  • 我更新了答案,希望对您有所帮助。 This example 为我正常工作。

标签: ruby-on-rails-4 mongoid slug


【解决方案1】:

您不能只复制该行 slug_id_strategy: lambda {|id| id.start_with?('....')} 而不进行更改。您应该将点替换为定义是否为 id 的内容。

来自文档:

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

所以,例如:

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 中:

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

还将field: _id 行更改为:

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

因为_id 类型不是字符串,会出现这个错误。这应该可以。

【讨论】:

  • 谢谢。是否必须有这一行 slug_id_strategy: lambda...,因此我想我需要先检查 name 变量以确保格式?
  • 不,这是附加代码,用于通过 id 而非名称查找对象。据我了解,您可以使用相同的find
  • 它给了我一个错误信息:语法错误,意外'=' ...d_strategy: lambda { |id| id ~= \^[A-z\d]+$\ } 用于 slug_id_strategy: lambda { |id| id ~= \^[A-z\d]+$\ }
  • 我真的很抱歉,但我不明白
  • 顺便说一句,答案附近有一个daw,如果它解决了问题,您应该接受它。我看到你没有接受 10 个中的任何一个,你可能不知道。检查tour
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-16
  • 1970-01-01
相关资源
最近更新 更多