2017-07-21 78 views
0

我已經在Rails 5中實現了一個簡單的搜索表單,該表單按標題查找位置。它起作用了,自從第一次實現它之後,我就沒有觸及代碼。自那時以來,我添加了幾個功能(分頁,充當可投票,標籤),出於某種原因,搜索表單不起作用。它出現的位置,標題被拉到正確:Rails搜索表單無法工作

/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

你在結果中得到什麼,全部或沒有位置? – archana

+0

@archana對不起,我應該把它包括在問題中。我收到所有結果。 –

+0

是否允許參數「搜索」?你可以在控制器中記錄這個值,看看你收到了什麼? – archana

回答

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 
+0

請查看我的更新回答 –

+0

謝謝@moustafa sallam。我試過用這兩個選項進行更新,它仍然不搜索在搜索字段中輸入的標題。我也嘗試在我的表單中改變params [:title]到[:search],這沒有什麼區別。仍然拉動所有地點。 –

+0

請給我看更新的代碼 –