【发布时间】:2014-09-20 04:27:20
【问题描述】:
我正在尝试在我的 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: no such column: ful_name: SELECT "users".* FROM "users" WHERE (first_name LIKE '%Spider Man' OR last_name LIKE '%Spider Man' OR ful_name LIKE '%Spider Man') ORDER BY created_at DESC
app/views/users/index.html.erb:5:in `_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 看起来是正确的,但是
This works for either first or last name but not both.是什么意思? -
它将根据我在数据库中的名字或姓氏字符串进行搜索,但不会搜索 first_name + last_name
标签: ruby-on-rails ruby ruby-on-rails-4 rails-activerecord