我想通過我的Rails應用程序中的名字和姓氏搜索用戶,目前我正在嘗試每種方法都得到混合結果。有沒有辦法重新編寫這些方法來獲得我想要的結果?試圖通過名字和姓氏搜索
user_controller.rb
方法#1
def self.search(query)
where("first_name LIKE ? OR last_name LIKE ?", "%#{query}%", "%#{query}%")
end
這適用於任何名字或姓氏,但不能同時使用。
方法2
def self.search(keywords)
if keywords
where(:all, :conditions => ["concat(first_name," ",last_name) like?", "%#{keywords}%"])
end
end
這不返回任何結果
方法#3
def self.search(search)
if search
select('(first_name || " " || last_name) as \'ful_name\', *')
where ['first_name LIKE :s OR last_name LIKE :s OR ful_name LIKE :s', :s => "%#{search}"]
else
scoped
end
end
這將返回錯誤
的SQLite3 ::的SQLException:沒有這樣的列:ful_name:SELECT「users」。* FROM「us ers「WHERE(first_name LIKE'%Spider Man'或last_name LIKE'%Spider Man'或ful_name LIKE'%Spider Man')ORDER BY created_at DESC
app/views/users/index.html.erb:5:在`_app_views_users_index_html_erb__848623016_40254132'
index.html.erb
<% provide(:title, 'Search') %>
<h1>Search</h1>
<ul class="span4 users">
<%= render @users %>
</ul>
_user.html.erb
<li>
<%= image_tag user.avatar(:medium) %>
<h4><%= link_to user.full_name, feed_user_path(user), :class => "follow-color" %></h4>
<% if current_user.admin? && !current_user?(user) %>
| <%= link_to "delete", user, method: :delete,
data: { confirm: "You sure?" } %>
<% end %>
</li>
_header.html。 ERB
<%= form_tag users_path, method: "get", class: "search-bar" do %>
<%= text_field_tag :search, params[:search], placeholder: "Search" %>
<% end %>
第一varitan看起來是正確的,但你是什麼意思'這適用於名字或姓氏,但不是兩個.'? – IS04 2014-09-20 04:36:53
它將通過我在數據庫中的名字或姓氏字符串進行搜索,但不會爲first_name + last_name搜索 – teddybear 2014-09-20 04:45:55