如何使用不依赖于数据库的条件创建可链接方法(范围)
我有一个模型Item
,它与其自身有关系。
class Item < ActiveRecord::Base
has_many :subitems, :class_name => "Item", :foreign_key => "superitem_id"
belongs_to :superitem, :class_name => "Item"
end
我想查询所有有父项的项目。首先,我尝试检查parent_id是否存在 Item.where("superitem_id != ?", false)
或类似的内容。但这不起作用。尽管该项目具有 superitem_id,但 superitem 可能已被销毁。所以我必须用类方法来做到这一点,
def self.with_superitems
items = []
self.find_each do |i|
items << i if i.superitem
end
return items
end
但这使得链接变得不可能,我想用类似的方法链接它,比如
def self.can_be_stored
items = []
self.find_each do |i|
items << i if i.can_be_stored?
end
return items
end
是否可以使用作用域实现相同的结果? 或者你会做什么?
I have a model Item
, which has a relation to itself.
class Item < ActiveRecord::Base
has_many :subitems, :class_name => "Item", :foreign_key => "superitem_id"
belongs_to :superitem, :class_name => "Item"
end
And I want to query all items which have a parent. Firstly I've tried to check if parent_id is present Item.where("superitem_id != ?", false)
, or something like this. But it doesn't work. Although that item has superitem_id, superitem can be already destroyed. So I have to do it with class method
def self.with_superitems
items = []
self.find_each do |i|
items << i if i.superitem
end
return items
end
But it makes chaining impossible, and I want to chain it with similar methods, like
def self.can_be_stored
items = []
self.find_each do |i|
items << i if i.can_be_stored?
end
return items
end
Is it possible to achieve the same results with scopes?
Or what would you do?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我过去也遇到过类似的问题。有时很难绕过它。我发现了一种出于我的目的的黑客方式,所以希望这会有所帮助......
I've had a similar issue in the past. It's sometimes difficult to get round it. I found a hack-ish way of doing it for my purposes so hope this will help...
在rails 2中,我会这样做,
rails3相当于这样,
您可以拉入父级并测试连接的superitem一侧的id字段是否有id。如果没有,那是因为那里没有超级项目(或者,从技术上讲,它可能在那里,但没有 id。但这通常不会发生)。
In rails 2 i would have done this
the rails3 equivalent of this is
This way you're pulling in the parent and testing if the id field on the superitem side of the join has an id. if it doesn't, it's because there's no superitem there (or, technically, it could be there but have no id. But this would normally never happen).
以下将获取具有父项的所有项目,我不确定当您说“虽然该项目具有 superitem_id,但 superitem 可能已被销毁”时的意思
The following will get all the items with a parent, I'm not sure what you mean when you say "Although that item has superitem_id, superitem can be already destroyed"