【问题标题】:Autocomplete multiple fields with jquery in Rails 5在 Rails 5 中使用 jquery 自动完成多个字段
【发布时间】:2018-09-17 18:46:18
【问题描述】:

我正在构建一个管理表单,其中我将 Jquery 的自动完成小部件用于其中一个文本字段。

在名为 customer_phone_number 的字段中,当有人键入电话号码时,自动完成功能会检查数据库是否存在并列出现有选项。选择电话号码后,我希望它填写另一个名为 customer_name 的字段。我已经设法自动完成第一个但不是另一个。这是我的代码现在的样子:

这是视图:

<div class="col-md-4 input">
  <div class="form-group">
    <label>Customer's Phone Number</label>
    <%= f.text_field :customer_phone_number, class: "form-control", data: { autocomplete_source: customers_path }  %>
  </div>
</div>
<div class="col-md-4 input">
  <div class="form-group">
    <label>Customer's Name</label>
    <%= f.text_field :customer_name, class: "form-control", data: { autocomplete_source: customers_path }  %>
  </div>
</div>

javascript 文件:

jQuery(function() {

  return $('#customer_phone_number').autocomplete({
    source: $('#customer_phone_number').data('autocomplete-source'),
    select: function(event, ui) {
      event.preventDefault(),
      $(this).val(ui.item.phone_number),
      $('#customer_name').val(ui.item.name);
    }
  });
});

和控制器:

  def index
    @customer = Customer.order(:phone_number).where("phone_number like ?", "%#{params[:term]}%").limit(5)
    render json: @customer.map{ |customer| { :phone_number => customer.phone_number, :name => customer.name } }
    # render json: @customer.pluck(:phone_number, :name)

  end

如何将 :name 值传递给 customer_name 字段?

【问题讨论】:

  • 它应该适用于您的代码。检查customer_nametext_field的id属性是否为customer_name
  • 是的,但自动完成列表似乎仍然是空的。你知道还有什么问题吗?非常感谢。
  • @Johnny 与您的代码有点混淆的是Customer 模型中的字段名称customer_phone_numberphone_number

标签: jquery ruby-on-rails ruby autocomplete


【解决方案1】:

您可能正在获取错误的查询,因为表单字段名称为customer_phone_number,而查询其为phone_number

假设在Customer 模型字段名称是customer_phone_number 那么查询应该是

def index
    @customer = Customer.order(:customer_phone_number).where("customer_phone_number like ?", "%#{params[:term]}%").limit(5)
    render json: @customer.map{ |customer| { :phone_number => customer.customer_phone_number, :name => customer.name } }

end

【讨论】:

  • 在客户模型中,字段名称是phone_number。
  • @Johnny 如果是这样,那你为什么在form_for 中使用customer_phone_number
  • 没有特别的原因。这就是我在另一个模型中引用它的方式,因为我认为没有 customer_ 会让人感到困惑,尤其是对于 _name 字段。不会吗?
  • 好的,那么您可以在rails 控制台customer = Customer.order(:phone_number).where("phone_number like ?", "%#{params[:term]}%").limit(5) 上运行您的查询,用您的params[:term] 替换您的query param 并在那里获得任何记录吗?
  • 不,它没有返回任何东西。我设法使它与一个属性一起工作的方法是使用 pluck: render json: @owner.pluck(:phone_number) 当我尝试使用 map 进行类似的操作时,它不起作用。
【解决方案2】:

我已经设法通过 rails-jquery-autocomplete gem 使用不同的方法使其工作:

https://github.com/risuiowa/rails-jquery-autocomplete/

使用

自动完成字段

结果证明更容易实现。 示例:

form_for @product do |f|
  f.autocomplete_field :brand_name, autocomplete_brand_name_products_path
end

【讨论】:

    猜你喜欢
    • 2013-04-05
    • 1970-01-01
    • 2013-03-01
    • 2013-07-12
    • 2012-12-15
    • 2011-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多