【问题标题】:params[:search] error after updating to Rails 4.1更新到 Rails 4.1 后的 params[:search] 错误
【发布时间】:2015-08-05 19:36:52
【问题描述】:

我最近将我的 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] : []))

控制器

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 %>

【问题讨论】:

  • 不足以回答,但在 Rails 4 中,all(conditions) 可能会被弃用。不管你是否应该使用where(attr1: value, attr2: value)
  • 您能告诉我发生此错误的params[:search] 的值吗?
  • "搜索"=>"指导、辅导"

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


【解决方案1】:

经过一个小时的搜索,我知道在 rails 4.1 以后的 all 方法 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

【讨论】:

  • 我正在尝试这个,但由于某种原因它返回每个值,就像说 self.all
  • 你传递给search方法的参数是什么?
猜你喜欢
  • 2015-10-28
  • 1970-01-01
  • 2020-06-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-24
  • 1970-01-01
相关资源
最近更新 更多