我正在尝试在我的 rails 应用程序中按名字和姓氏搜索用户,并且目前我尝试的每种方法都得到了不同的结果。有没有办法重写这些方法中的任何一个以获得我想要的结果?
用户控制器.rb
方法#1
def self.search(query)
where("first_name LIKE ? OR last_name LIKE ?", "%#{query}%", "%#{query}%")
end
Run Code Online (Sandbox Code Playgroud)
这适用于名字或姓氏,但不适用于两者。
方法#2
def self.search(keywords)
if keywords
where(:all, :conditions => ["concat(first_name," ",last_name) like?", "%#{keywords}%"])
end
end
Run Code Online (Sandbox Code Playgroud)
这不会返回任何结果
方法#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
Run Code Online (Sandbox Code Playgroud)
这将返回错误
SQLite3::SQLException: 没有这样的列:ful_name: SELECT "users".* FROM "users" WHERE (first_name LIKE '%Spider Man' OR last_name …
我可以将哈希集更新为另一个变量,如下所示:
d = a = {b: 'c'}
a[:b] = 'qwerty'
d # => {:b=>'qwerty'} # What is this magic?
d[:b] = 'blah'
a # => {:b=>'blah'} # And this magic?
Run Code Online (Sandbox Code Playgroud)
为什么在使用原始变量时不会发生这种情况?
d = a = 'b'
a = 'c'
d # =>'b' # Why is it still the same?
Run Code Online (Sandbox Code Playgroud) 从数组:
this = [1, 2, 3, 4, 5]
Run Code Online (Sandbox Code Playgroud)
我正在尝试创建哈希哈希:
{{num: 1}, {num: 2}, {num: 3}, {num: 4}, {num: 5}}
Run Code Online (Sandbox Code Playgroud)
但我得到一个空哈希:
Hash.new(this.each do |num| Hash.new(num: num) end)
# => {}
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?