更新到Rails 4.1后{para} [:search]错误

时间:2015-08-05 19:36:52

标签: ruby search ruby-on-rails-4.1 mysql2

我最近将我的Rails应用程序从4.0更新到4.1。一切似乎都运行良好,除了我之前工作的Resource_Tag模型中的这一行。

基本上,我想按标签名称和District_Resource名称搜索/查找District_Resources。

**ex.**
If I search the word "Tutoring" 
*I should get all District_Resources with the Resource_Tag "Tutoring"
*And all District Resources that include the word Tutoring in it's Name. 
(i.e Tutoring Services)

出于某种原因,我不断收到此错误:

wrong number of arguments (1 for 0)
all(:conditions =>  (string ? [cond_text, *cond_values] : []))

CONTROLLER

class ResourceTagsController < ApplicationController

  def index    
    if params[:search].present?

      #Calls Search Model Method
      @resource_tags = ResourceTag.search(params[:search])
      @tagsearch = ResourceTag.search(params[:search])
      @tag_counts = ResourceTag.count(:group => :name, 
        :order => 'count_all DESC', :limit => 100)
    else
      @resource_tags = ResourceTag.all
    end
  end

end

模型

class DistrictResource < ActiveRecord::Base

  has_many :district_mappings, dependent: :destroy
  has_many :resource_tags, through: :district_mappings

  accepts_nested_attributes_for :resource_tags
end

class ResourceTag < ActiveRecord::Base

  #create relationships with all resource and mapping models
  has_many :district_mappings, dependent: :destroy
  has_many :district_resources, through: :district_mappings

  #I GET AN ERROR HERE
  def self.search(string)
    return [] if string.blank?

    cond_text = string.split(', ').map{|w| "name like ?"}.join(" OR ")   

    cond_values = string.split(', ').map{|w| "%#{w}%"}

    all(:conditions =>  (string ? [cond_text, *cond_values] : []))
  end

end

视图

<%= form_tag(resource_tags_path, :method => 'get', class: "navbar-search") do %>
  <form>
    <%= text_field_tag :search, params[:search], :class => "search-query form-control" %>
    <%= submit_tag "Search", :name => nil, :class => "search-button" %>
  </form>
<% end %>

1 个答案:

答案 0 :(得分:1)

经过一个小时的搜索后,我发现all的In rails 4.1 onward ActiveRecord方法没有采用任何参数,这就是为什么会出现额外的参数错误。您可以尝试使用where。这是您的搜索方法

def search(string)

return [] if string.blank?

cond_text = string.split(', ').map{|w| "name like ?"}.join(" OR ")   

cond_values = string.split(', ').map{|w| "%#{w}%"}

self.where(string ? [cond_text, *cond_values] : [])

end