我在Rails 5中实现了一个简单的搜索表单,它按标题查找位置。它工作正常,自从第一次实现它以来我没有触及过代码。我从那以后添加了几个功能(分页,充当可投票,标签),并且由于某种原因搜索表单不起作用。看起来正确地拉入了位置标题:
/位置UTF8 =✓&安培;标题=布伦特伍德
问题在于所有位置都被拉入,而不是被搜索的位置。
是否有阻止此工作的东西?
class Location < ApplicationRecord
geocoded_by :address
after_validation :geocode
acts_as_votable
extend FriendlyId
friendly_id :title, use: :slugged
def should_generate_new_friendly_id?
new_record?
end
def self.search(search)
if search
where("LOWER(search) LIKE ?", "%#{search.to_s.downcase}%")
else
all
end
end
belongs_to :user
has_attached_file :image,
styles: { large: "", medium: "300x300#", thumb: "100x100#" },
storage: :s3,
:s3_protocol => :https,
url: ":s3_domain_url",
default_url: "placeholder.jpg",
path: "/:class/:attachment/:id_partition/:style/:filename",
s3_region: ENV["S3_REGION"],
s3_credentials: Proc.new { |a| a.instance.s3_credentials }
def s3_credentials
{
bucket: ENV['S3_BUCKET_NAME'],
access_key_id: ENV['S3_ACCESS_KEY_ID'],
secret_access_key: ENV['S3_SECRET_ACCESS_KEY'],
}
end
acts_as_taggable
validates_attachment_content_type :image, content_type: /\Aimage\/.*\z/
has_many :comments, dependent: :destroy
end
这是我的locations_controller.rb文件
if params[:search]
@locations = Location.search(params[:search]).order("created_at DESC")
else
@locations = Location.all.order('created_at DESC')
end
这是我的搜索表单:
<%= form_tag locations_path, method: :get do %>
<p>
<%= text_field_tag :search, params[:search], placeholder: "Look for your spot!" %>
<%= submit_tag "Search", name: nil %>
</p>
<% end %>
我尝试过多种尚未解决的解决方案。
答案 0 :(得分:0)
您正在发送 params[:title]
当您在控制器中寻找 params[:search]
时
您可以更改text_field_tag name attribute to search
或更改Controller action to look for params[:title] instead of params[:search]
另请注意,您正在使用区分大小写的LIKE
进行搜索。您的搜索方法应该调整如下:
def self.search(search)
if search
where("LOWER(title) LIKE ?", "%#{search.to_s.downcase}%")
else
all
end
end
如果您使用的是PG,可以使用ILIKE
def self.search(search)
if search
where("title ILIKE ?", "%#{search.to_s.downcase}%")
else
all
end
end