我如何将其转换为 MetaWhere 或 Arel?
考虑一个城市模型具有:
def self.search(field, search)
if search
where("#{field} LIKE ?", "%#{search}%")
else
scoped
end
end
在知道该字段是字符串的情况下如何使用 Arel 或 Metawhere 可以具有类似:
“名称”的 内容 “居民姓名” “state.name”
我想做类似的事情(行不通):
def self.search(field, search)
if search
where(field =~ "%#{search}%")
else
scoped
end
end
那么,你的想法是什么?
真正的问题是,我怎样才能将其转换为:
“residents.name LIKE '#{value}%'”
到:
:residents => { :name =~ "#{value}%" }
Consider a City Model having:
def self.search(field, search)
if search
where("#{field} LIKE ?", "%#{search}%")
else
scoped
end
end
How can I use Arel or Metawhere in that situation knowing that field is a String can have anything like:
"name"
"residents.name"
"state.name"
I want to do something like that (will not work):
def self.search(field, search)
if search
where(field =~ "%#{search}%")
else
scoped
end
end
So, what are your thoughts?
The real question is, how can I convert that:
"residents.name LIKE '#{value}%'"
To that:
:residents => { :name =~ "#{value}%" }
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你应该能够像这样使用 Arel。
有一个 Railscast 很好地解释了以下基础知识在 Rails 3 中使用 Arel。
You should be able to use Arel like this.
There's a Railscast that does a good job of explaining the basics of using Arel in Rails 3.