RAILS:复杂的查找条件

发布于 2024-10-23 18:40:58 字数 289 浏览 1 评论 0原文

假设我们有这样的模型:

触发器 属于 :position

位置 has_many :trigger

Position 有一些字段,包括 :posx、:poxy,也许还有一些我们想要过滤的其他字段......

本质上。在触发器控制器中,我想找到属于 posx 和 posy 某个范围内的所有触发器。

我已经在 cakephp 的一个查询中完成了这一点,所以我知道它应该是可能的,但我不知道如何在 Rails 中构建它。此外,我不知道如何做“和”和“或”等...

谢谢!

Let us say we have models as such:

Trigger
belongs_to :position

Position
has_many :trigger

Position has a few fields including :posx, :poxy, and maybe few other fields we would like to filter by...

Essentially. Within the triggers_controller, I would like to find all triggers that fall within some range of posx and posy.

I've done this in one query in cakephp so I know it should be possible, but I don't know how to structure this in rails. Furthermore, I don't know how to do "and" and "or" etc...

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

栩栩如生 2024-10-30 18:40:58

我将创建一个范围来处理这种潜在的常见查找:

class Trigger < ActiveRecord::Base

  belongs_to :position

  # if you're in rails 2
  named_scope :within, lambda{|tlx, tly, brx, bry| {:joins => :position, conditions => ['`positions`.posx >= ? AND `positions`.posy >= ? AND `positions`.posx <= ? AND `positions`.posy <= ?', tlx, tly, brx, bry]} }

  # if you're in rails 3
  scope :within, lamba{|tlx,tly,brx,bry| joins(:position).where('`positions`.posx >= ? AND `positions`.posy >= ? AND `positions`.posx <= ? AND `positions`.posy <= ?', tlx, tly, brx, bry) }
end

然后在您的控制器中您只需执行以下操作:

Trigger.within(top_left_x, top_left_y, bottom_right_x, bottom_right_y)

I would create a scope to handle this sort of potentially common lookup:

class Trigger < ActiveRecord::Base

  belongs_to :position

  # if you're in rails 2
  named_scope :within, lambda{|tlx, tly, brx, bry| {:joins => :position, conditions => ['`positions`.posx >= ? AND `positions`.posy >= ? AND `positions`.posx <= ? AND `positions`.posy <= ?', tlx, tly, brx, bry]} }

  # if you're in rails 3
  scope :within, lamba{|tlx,tly,brx,bry| joins(:position).where('`positions`.posx >= ? AND `positions`.posy >= ? AND `positions`.posx <= ? AND `positions`.posy <= ?', tlx, tly, brx, bry) }
end

Then in your controller you would just do:

Trigger.within(top_left_x, top_left_y, bottom_right_x, bottom_right_y)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文