HABTM 检查最新 3 项的匹配

发布于 2024-08-31 18:54:12 字数 594 浏览 8 评论 0原文

对于你们来说,这是一个有趣的关系......

我在“狗”和“旅行”之间有一个 HABTM(has_and_belongs_to_many)关系。我的目标是找到两个结果集: 1) 过去 3 次旅行中至少有 1 次的狗,并称其为 @dogs_current 2) 没有参加过最近 3 次旅行的狗并称其为 @dogs_old

我发现我可以通过在 Trip 模型中执行此操作来找到最近 3 次旅行:

  named_scope :last3, :order => 'date DESC', :limit => 3

但不确定如何使用该列表 get 1 和2. 这个 hack 有效,但看起来很丑。一定有更好的办法! :)

@dogs_current = []
@dogs_old = []
@dogs.each do |dog| 
  if (Trip.last3 - dog.trips).size < 3 then
    @dogs_current << dog
  else
    @dogs_old << dog
  end
end

有什么想法吗?谢谢! -凸轮

Here's an interesting one for you folks...

I have a HABTM (has_and_belongs_to_many) relationship between "Dogs" and "Trips". My goal is to find two result sets:
1) Dogs that have been on at least 1 of the last 3 trips and call that @dogs_current
2) Dogs that have NOT been on any of the last 3 trips and call that @dogs_old

I found that I can find what the last 3 trips are by doing this in the Trip model:

  named_scope :last3, :order => 'date DESC', :limit => 3

But not sure how to use that list get 1 and 2. This hack works, but it seems ugly. There must be a better way! :)

@dogs_current = []
@dogs_old = []
@dogs.each do |dog| 
  if (Trip.last3 - dog.trips).size < 3 then
    @dogs_current << dog
  else
    @dogs_old << dog
  end
end

Any ideas? Thanks!
-Cam

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

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

发布评论

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

评论(1

情绪失控 2024-09-07 18:54:12
class Trip < ActiveRecord::Base
   has_and_belongs_to_many :dogs
   named_scope :last3, :order => 'date DESC', :limit => 3
end

class Dog < ActiveRecord::Base
   has_and_belongs_to_many :trips
end

#IDs of last 3 trips
last_trips_ids = Trip.last3.collect(&:id)

# I'm assuming your join table is `dogs_trips`.
@dogs_current = Dog.all(:joins => :trips,
   :conditions => ["dogs_trips.trip_id IN (?)", last_trips_ids]).uniq

@dogs_old = Dog.all(:joins => :trips,
   :conditions => ["dogs_trips.trip_id NOT IN (?)", last_trips_ids]).uniq

我相信这是正确的。至少对我来说在这里工作......

class Trip < ActiveRecord::Base
   has_and_belongs_to_many :dogs
   named_scope :last3, :order => 'date DESC', :limit => 3
end

class Dog < ActiveRecord::Base
   has_and_belongs_to_many :trips
end

#IDs of last 3 trips
last_trips_ids = Trip.last3.collect(&:id)

# I'm assuming your join table is `dogs_trips`.
@dogs_current = Dog.all(:joins => :trips,
   :conditions => ["dogs_trips.trip_id IN (?)", last_trips_ids]).uniq

@dogs_old = Dog.all(:joins => :trips,
   :conditions => ["dogs_trips.trip_id NOT IN (?)", last_trips_ids]).uniq

I believe this is correct. At least worked here for me...

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