【问题标题】:ActiveRecord::RecordNotFound (Couldn't find User with 'id'=json)ActiveRecord::RecordNotFound(找不到 'id'=json 的用户)
【发布时间】:2019-08-01 03:06:03
【问题描述】:

我正在开发我的 Rails 应用程序中的自动完成功能,并遵循 How to set-up jquery-ui autocomplete in Rails 的回答。当我在input 中输入内容时,会出现此错误:ActiveRecord::RecordNotFound (Couldn't find User with 'id'=json)? (:term 仍然等于我输入的任何内容)为什么会有id=json

<div>
  <input id="select_user" />
  <input id="link_user_id" name="link[user_id]" type="hidden"/>
</div>

<script type="text/javascript">
  $(function() {
    $('#select_user').autocomplete({
      minLength: 1,
      source: '<%= user_path(:json) %>',
    })
    .data("ui-autocomplete")._renderItem = function( ul, item ) {
      return $( "<li></li>" )
        .data( "ui-autocomplete-item", item )
        .append( "<a>" + item.user.name + "</a>" )
        .appendTo( ul );
    };
  });
</script>

用户控制器:

def index
  if params[:term]
    @users = User.find(:all, :conditions => ['name LIKE ?', "%#{params[:term]}%"])
  end

  respond_to do |format|
    format.html
    format.json { render :json => @users.to_json }
  end
end

【问题讨论】:

  • 您使用的是什么版本的导轨?较新版本的 Rails 不支持 User.find(:all) 尝试User.where()
  • @Vbp,它是 5.0.1
  • 试试这样的User.where("name LIKE ?", "%#{params[:term]}%")
  • 刚刚尝试过,但得到相同的错误Couldn't find User with 'id'=json。我想知道它是否与这一行有关 'source: ''`
  • 这看起来像是一个不同的错误,它说找不到字体而不是用户?

标签: jquery ruby-on-rails


【解决方案1】:

你的问题在这里:

source: '<%= user_path(:json) %>'

传递给这些 url 帮助程序的第一个属性始终是 objectid。因此,您的问题远在 cmets 中提到的所有内容之前。

user_path({}, format: :json) 是否用于添加格式。这个剪断将可能返回ActiveRecord::RecordNotFound (Couldn't find User with 'id'=nil)。所以你得想办法把id传入。

我猜你希望所有用户都在index 操作中返回匹配项。为此,您必须使用users_path(format: :json)

【讨论】:

    【解决方案2】:

    尝试更新的语法

    User.where("name LIKE ?", "%#{params[:term]}%")
    

    我认为您使用的语法在 rails 3 中已弃用

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-21
      • 1970-01-01
      • 2017-03-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多