我想通过我的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