簡體   English   中英

使用Rails將搜索結果發送到JSON

[英]Send search results to json with rails

我目前正在使用Rails應用程序上的簡單搜索功能。 我正在使用Vue.js,因此我將使用Rails的JSON構建器將所有內容饋送到前端。 對於搜索,我具有如下控制器和模型設置:

控制器:

def index
  if params[:search]
    @strains = Strain.search(params[:search]).order("created_at DESC")
  else
    @strains = Strain.all.order("created_at DESC")
  end
  respond_to do |format|
    format.html
    format.json { render :json => @strains }
  end
end

該模型:

  def self.search(search)
    where('title LIKE ?', '%#{search}%')
  end

風景:

<%= form_tag(strains_path, :method => "get") do %>
  <%= text_field_tag :search, params[:search], placeholder: "Search Strains" %>
  <%= submit_tag "Search", :name => nil %>
<% end %>

當我輸入搜索內容時,我看到它更新了URL中的參數,但是頁面上的輸出沒有任何反應。 我在想它與JSON有關。 這是我在Vue組件中准備好的功能。

ready: function() {
    var that;
    that = this;
    $.ajax({
      url: '/strains.json',
      success: function(res){
        that.strains = res;
      }
    });
  }

我正在查看日志,似乎它將呈現HTML而不是JSON的搜索。

這是日志:

Started GET "/strains.json" for ::1 at 2016-05-23 21:40:32 -0400
Processing by StrainsController#index as JSON
  Strain Load (0.2ms)  SELECT "strains".* FROM "strains"  ORDER BY created_at DESC
Completed 200 OK in 2ms (Views: 1.8ms | ActiveRecord: 0.2ms)


Started GET "/strains?utf8=%E2%9C%93&search=Test" for ::1 at 2016-05-23 21:41:07 -0400
Processing by StrainsController#index as HTML
  Parameters: {"utf8"=>"✓", "search"=>"Test"}
  Strain Load (0.2ms)  SELECT "strains".* FROM "strains" WHERE (title LIKE '%Test%')  ORDER BY created_at DESC
  Rendered strains/index.html.erb within layouts/application (1.5ms)
Completed 200 OK in 17ms (Views: 16.3ms | ActiveRecord: 0.2ms)


Started GET "/strains.json" for ::1 at 2016-05-23 21:41:07 -0400
Processing by StrainsController#index as JSON
  Strain Load (0.1ms)  SELECT "strains".* FROM "strains"  ORDER BY created_at DESC
Completed 200 OK in 2ms (Views: 1.4ms | ActiveRecord: 0.1ms)

我不確定這是否是您的主要問題,但它看起來您的where子句使用的是單引號,因此沒有選擇該變量。 如果要使用紅寶石字符串插值,則需要使用雙引號。

irb(main):006:0> foo = 5
=> 5
irb(main):007:0> 'this is my number #{foo}'
=> "this is my number \#{foo}"
irb(main):008:0> "this is my number #{foo}"
=> "this is my number 5"

所以你要:

  def self.search(search)
    where('title LIKE ?', "%#{search}%")
  end

您應該將dataType選項設置為期望JSON數據作為返回值。 您可以這樣做:

$.ajax({
  url: '/strains.json',
  dataType: 'json',
  success: function(res){
    that.strains = res;
  }
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM