【问题标题】:rails4-autocomplete not workingrails4-autocomplete 不工作
【发布时间】:2014-04-28 06:07:17
【问题描述】:

尝试在我的 rails 4 应用程序中使用 this gem 自动完成。我正在尝试让我的评论表单在用户输入艺术家姓名时自动完成(如果它已经存在于数据库中)。

按照示例,在我的评论控制器中放置

class ReviewsController < ApplicationController
  autocomplete :review, :artist

在 application.js 中:

//= require jquery
//= require jquery_ujs
//= require jquery-ui
//= require autocomplete-rails
//= require turbolinks
//= require bootstrap
//= require bootstrap-scrollspy
//= require bootstrap-modal
//= require bootstrap-dropdown
//= require_tree .

在路线中:

resources :reviews do
    get :autocomplete_review_artist, :on => :collection
end

在我的评论表顶部:

<%= form_for(@review) do |f| %>
<% f.autocomplete_field :artist, autocomplete_review_artist_reviews_path %>

审查模型:

class Review < ActiveRecord::Base

    validates_presence_of :artist
    validates_presence_of :venue
    validates_presence_of :date

    belongs_to :user
    belongs_to :concert

end

但它不起作用,当我尝试在已创建的表单中输入艺术家姓名时,没有任何东西可以自动完成它。任何帮助表示赞赏。

我还尝试在 2 个单独的控制器中完全按照示例的完成方式进行操作。还是不行。

在我的艺术家控制器中

class ArtistsController < ApplicationController
  before_action :set_artist, only: [:show, :edit, :update, :destroy]

  autocomplete :artist, :name

然后在路线中

resources :reviews do
    get :autocomplete_artist_name, :on => :collection
  end

和审核表

<%= form_for(@review) do |f| %>
  <% f.autocomplete_field :artist, autocomplete_artist_name_reviews_path %>

【问题讨论】:

    标签: jquery ruby-on-rails-4 autocomplete gem


    【解决方案1】:

    我认为通过在 JS 数组中执行它来提高响应性,你会得到更好的结果。 为此,您需要使用 .as_json 方法在控制器上渲染一个变量。

    所以,在控制器中(参数是说明性的):

    @autocompleteArr = Object.pluck(:property).as_json
    

    在视图中:

    <%= f.text_field :somefield %>
    

    在 JS 中(你不能把它放在你的应用程序文件甚至你的 html 中):

    $('#somefield').autocomplete({source: '<%=raw  @autocompleteArr %>'});
    

    您会看到,在这种情况下,更容易并防止 ajax 加载时间可能会使您的使用体验变差。

    希望对你有帮助。

    【讨论】:

      【解决方案2】:

      assets/javascripts中创建了一个artist.js.erb
      内容是:
      $(function() { var artists = <%Artist.All.collect{|artist| artist.name}%> $( "#artistReview" ).autocomplete({ source: artists }); });
      将其包含在视图中。使用 include_javascript_tag
      给出需要自动完成的字段id: 'artistReview'

      分别在 application.js 中需要 jquery-ui//code.jquery.com/jquery-1.10.2.js//code.jquery.com/ui/1.10.4/jquery-ui.js 。并且解决了这个问题,但是必须进行广泛的样式化

      【讨论】:

      • 其他行已经在里面了,抱歉不清楚
      • 还有其他建议吗?文档似乎很少,所以我很难找到我的问题
      • 我在上面加了,很标准。
      • 这里和他们的文档唯一的区别是他们将艺术家放在一个单独的模型中,而您的评论有艺术家。试试看。实际上这是更好的做法,创建一个 has_many 关系,artist 有很多评论。试试看。
      • 试过了还是不行,更新原帖
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-22
      • 2019-12-05
      • 2012-02-29
      • 1970-01-01
      相关资源
      最近更新 更多