我目前正在研究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中的params,但页面上的输出没有任何反应。我认为它与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)
答案 0 :(得分:0)
我不确定这是否是您的主要问题,但它看起来您的where子句使用单引号,因此不会获取该变量。如果要使用ruby字符串插值,则需要使用双引号。
Applications
所以你想要:
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"
答案 1 :(得分:0)
您应该设置dataType
选项以期望返回值的JSON数据。你可以这样做:
$.ajax({
url: '/strains.json',
dataType: 'json',
success: function(res){
that.strains = res;
}
});