如果遇到正确的id,那么在使用friendly_id gem时会出现问题

时间:2015-09-29 01:28:51

标签: jquery mysql ruby-on-rails ruby friendly-id

所以我正在为学校建立一个网站,其中包含用户可以创建,更新,编辑等的不同wiki。在我的wiki编辑页面上,我允许高级用户选择将协作者添加或删除到他们拥有的wiki如果他们选择将他们的维基检查为私有,则会创建。

我将此添加/删除协作者功能设计为与AJAX一起使用,以便用户可以与他们选择添加或删除的其他用户来回切换,而无需刷新页面。

在我实现了friendly_id gem之前,我的添加/删除功能工作正常。但是,在实现了friendly_id gem之后,我注意到了一个已经创建的新bug。让我解释..

每当我点击将用户添加为协作者时,事情看起来好像已经有效,我可以在添加和删除之间来回切换。但是,我最初尝试添加的用户没有被添加为协作者,并且在堆栈跟踪中很明显。

这是第一次点击“添加”链接后发生的情况:

Started POST "/wikis/hipsters/collaborators?user_id=3" for 127.0.0.1 at 2015-09-28 17:51:06 -0700
Processing by CollaboratorsController#create as JS
  Parameters: {"user_id"=>"3", "wiki_id"=>"hipsters"}
  Wiki Load (0.2ms)  SELECT  "wikis".* FROM "wikis"  WHERE "wikis"."slug" = 'hipsters'  ORDER BY "wikis"."id" ASC LIMIT 1
   (0.1ms)  begin transaction
  SQL (0.4ms)  INSERT INTO "collaborators" ("created_at", "updated_at", "user_id", "wiki_id") VALUES (?, ?, ?, ?)  [["created_at", "2015-09-29 00:51:06.185794"], ["updated_at", "2015-09-29 00:51:06.185794"], ["user_id", 3], ["wiki_id", 0]]
   (85.8ms)  commit transaction
   (0.1ms)  begin transaction
   (0.1ms)  commit transaction
   (0.2ms)  SELECT COUNT(*) FROM "collaborators"  WHERE "collaborators"."wiki_id" = ?  [["wiki_id", 51]]
  Rendered collaborators/create.js.haml (3.0ms)
Completed 200 OK in 198ms (Views: 106.9ms | ActiveRecord: 86.8ms)

注意如何尝试使用["user_id", 3], ["wiki_id", 0]

创建新的协作者

user_id是正确的,但wiki_id不是。为什么会这样? friendly_id gem正在工作,你可以看到这个特定维基的名字是“赶时髦的人”。

这在这里显而易见:

Parameters: {"user_id"=>"3", "wiki_id"=>"hipsters"}
  Wiki Load (0.2ms)  SELECT  "wikis".* FROM "wikis"  WHERE "wikis"."slug" = 'hipsters'  ORDER BY "wikis"."id" ASC LIMIT 1

但是,由于我只是试图将用户“添加”为协作者,现在链接已切换为“删除”,以摆脱协作者。

单击以删除协作者后,我的服务器日志显示以下内容:

Started DELETE "/wikis/51/collaborators/54" for 127.0.0.1 at 2015-09-28 18:02:39 -0700
Processing by CollaboratorsController#destroy as JS
  Parameters: {"wiki_id"=>"51", "id"=>"54"}
  Wiki Load (0.3ms)  SELECT  "wikis".* FROM "wikis"  WHERE "wikis"."slug" = '51'  ORDER BY "wikis"."id" ASC LIMIT 1
  Wiki Load (0.1ms)  SELECT  "wikis".* FROM "wikis"  WHERE "wikis"."id" = ? LIMIT 1  [["id", 51]]
  Collaborator Load (0.1ms)  SELECT  "collaborators".* FROM "collaborators"  WHERE "collaborators"."id" = ? LIMIT 1  [["id", 54]]
   (0.1ms)  begin transaction
  SQL (0.4ms)  DELETE FROM "collaborators" WHERE "collaborators"."id" = ?  [["id", 54]]
   (30.1ms)  commit transaction
   (0.2ms)  SELECT COUNT(*) FROM "collaborators"  WHERE "collaborators"."wiki_id" = ?  [["wiki_id", 51]]
  Rendered collaborators/destroy.js.haml (2.0ms)
Completed 200 OK in 52ms (Views: 16.1ms | ActiveRecord: 31.3ms)

然后,当我切换为再次将用户添加为协作者时,这次他们实际上已添加。

服务器日志:

Started POST "/wikis/51/collaborators?user_id=3" for 127.0.0.1 at 2015-09-28 18:05:59 -0700
Processing by CollaboratorsController#create as JS
  Parameters: {"user_id"=>"3", "wiki_id"=>"51"}
  Wiki Load (0.2ms)  SELECT  "wikis".* FROM "wikis"  WHERE "wikis"."slug" = '51'  ORDER BY "wikis"."id" ASC LIMIT 1
  Wiki Load (0.1ms)  SELECT  "wikis".* FROM "wikis"  WHERE "wikis"."id" = ? LIMIT 1  [["id", 51]]
   (0.1ms)  begin transaction
  SQL (0.7ms)  INSERT INTO "collaborators" ("created_at", "updated_at", "user_id", "wiki_id") VALUES (?, ?, ?, ?)  [["created_at", "2015-09-29 01:05:59.564379"], ["updated_at", "2015-09-29 01:05:59.564379"], ["user_id", 3], ["wiki_id", 51]]
   (182.8ms)  commit transaction
   (0.1ms)  begin transaction
   (0.1ms)  commit transaction
   (0.2ms)  SELECT COUNT(*) FROM "collaborators"  WHERE "collaborators"."wiki_id" = ?  [["wiki_id", 51]]
  Rendered collaborators/create.js.haml (3.1ms)
Completed 200 OK in 198ms (Views: 8.3ms | ActiveRecord: 184.2ms)

我注意到这次参数读取Parameters: {"user_id"=>"3", "wiki_id"=>"51"}而不是Parameters: {"user_id"=>"3", "wiki_id"=>"hipsters"}

这是为什么?如何才能使此功能正常运行?

以下是一些相关文件:

wikis_controller.rb:

class WikisController < ApplicationController
  def index
    @wikis = policy_scope(Wiki)
  end

  def show
    @wiki = Wiki.friendly.find(params[:id])
  end

  def new
    @wiki = Wiki.new

    authorize @wiki # Example
  end

  def create
    @wiki = Wiki.new(wiki_params)

    @wiki.user = current_user

    authorize @wiki

    if @wiki.save
      flash[:notice] = "Wiki was saved."
      redirect_to @wiki
    else
      flash[:error] = "There was an error saving the wiki.  Please try again."
      render :new
    end
  end

  def edit
    @wiki = Wiki.friendly.find(params[:id])
    @users = User.all

    authorize Wiki, :edit?
  end

  def update
    @wiki = Wiki.friendly.find(params[:id])

    authorize @wiki

    if @wiki.update_attributes(wiki_params)
      flash[:notice] = "Wiki was updated."
      redirect_to @wiki
    else
      flash[:error] = "There was an error saving the wiki.  Please try again."
      render :edit
    end
  end

  def destroy
    @wiki = Wiki.friendly.find(params[:id])

    authorize Wiki, :destroy?

    if @wiki.destroy
      flash[:notice] = "\"#{@wiki.title}\" was deleted successfully."
      redirect_to wikis_path
    else
      flash[:error] = "There was an error deleting the wiki."
      render :show
    end
  end

  private

  def wiki_params
    params.require(:wiki).permit(:title, :body, :private)
  end
end

collaborators_controller.rb:

class CollaboratorsController < ApplicationController
  def create
    @wiki = Wiki.friendly.find(params[:wiki_id])
    @collaborator = Collaborator.create(wiki_id: params[:wiki_id], user_id: params[:user_id])

    respond_to do |format|
      format.html
      format.js
    end
  end

  def destroy
    @wiki = Wiki.friendly.find(params[:wiki_id])
    @collab = Collaborator.find(params[:id])
    @user_id = @collab.user_id
    @collab.destroy

    respond_to do |format|
      format.html
      format.js
    end
  end
end

协作者/ create.js.haml:

- if @collaborator.save
  $('#'+#{ params[:user_id] }).replaceWith('<a data-method="delete" data-remote="true" href="/wikis/'+#{ @wiki.id }+'/collaborators/'+#{ @collaborator.id }+'" id="#{ @collaborator.user_id }" rel="nofollow">Remove</a>');
  $('.js-collaborators-count').html("Currently #{ pluralize(@wiki.collaborators.count, 'collaborator') } on this wiki.");
- else
  $('#'+#{ params[:user_id] }).prepend("<div class='alert alert-danger'>#{ flash[:error] = 'Oops something went wrong..' }</div>");

协作者/ destroy.js.haml:

- if @collab.destroyed?
  $('#'+#{ @user_id.to_s }).replaceWith('<a data-method="post" data-remote="true" href="/wikis/'+#{ @wiki.id }+'/collaborators?user_id=#{ @user_id }" id="#{ @user_id }" rel="nofollow">Add</a>');
  $('.js-collaborators-count').html("Currently #{ pluralize(@wiki.collaborators.count, 'collaborator') } on this wiki.");
- else
  $('#'+#{ @user_id.to_s }).prepend("<div class='alert alert-danger'>#{ flash[:error] = 'Oops something went wrong..' }</div>");

维基/ edit.html.haml:

%h1 Edit Wiki

.row
  .col-md-8
    = form_for @wiki do |f|
      .form-group
        = f.label :title
        = f.text_field :title, class: 'form-control', placeholder: "Enter wiki title"
      .form-group
        = f.label :body
        = f.text_area :body, rows: 8, class: 'form-control', placeholder: "Enter wiki body"

      - if current_user.role == 'admin' || (current_user.role == 'premium' && @wiki.user == current_user)
        = render 'wikis/form', f: f

      - if current_user.role == 'admin' || (@wiki.private == true && @wiki.user == current_user)
        .form-group
          %h5
            Add/Remove Collaborators to the
            %em &ldquo;#{ @wiki.title }&rdquo;
            wiki (Showing all users)
          %small
            .js-collaborators-count
              Currently #{ pluralize(@wiki.collaborators.count, 'collaborator') } on this wiki.
          .col-sm-4.text-center.outline
            %h6.underline Name
            - @users.each do |u|
              .border_bottom
                = u.name
                %br/

          .col-sm-4.text-center.outline
            %h6.underline Email
            - @users.each do |u|
              .border_bottom
                = u.email

          .col-sm-4.text-center.outline
            %h6.underline Give Access
            - @users.each do |u|
              .border_bottom
                - if collab = u.collaborators.find_by(wiki_id: @wiki.id)
                  = link_to "Remove", wiki_collaborator_path(@wiki, collab), method: :delete, remote: true, id: u.id
                - else
                  = link_to "Add", wiki_collaborators_path(@wiki, user_id: u.id), method: :post, remote: true, id: u.id

      .form-group
        = f.submit "Update", class: 'btn btn-success mt_10'

如果我留下任何文件,你可以在这里查看我在github上的回购:

https://github.com/jlquaccia/blocipedia

1 个答案:

答案 0 :(得分:0)

弄清楚出了什么问题。在创建动作中的collaborators_controller里面,我不得不改变

@collaborator = Collaborator.create(wiki_id: params[:wiki_id], user_id: params[:user_id])

@collaborator = Collaborator.create(wiki_id: @wiki.id, user_id: params[:user_id])

params[:wiki_id]定位于@wiki.id

时,目标是friendly_id slug