Ruby 在 Rails 上:为什么我的数组集包含 null,通过了我的 null 检查器?
Ruby on Rails: Why does my array set contain null, passing my null checker?
我的代码如下所示:
*movie_requests is a scope
def self.records (producer_id = 0)
actor_list = Array.new
movie_requests(producer_id).find_each do |studio|
actor = studio.actors.pluck(:id).uniq
if (!actor_list.include? actor) && (!actor.nil?)
actor_list << actor
end
end
return actor_list
end
最初在数据库中,它有这些演员 ID:
[[12305], [3749], [1263], [], [], [1263], [], [12305], []]
.pluck 和 .uniq 使每个工作室的冗余 ID 不同,但是 []
仍然存在:
[[12305], [3749], [1263], []]
为什么我的 && (!actor.nil?)
条件没有捕获空 ID 并使其成为一个独特的对象?
Edit: return actor_list.compact
also doesn't work
您可以检查 actor
是否存在,然后将此 actor
添加到 actor_list
为什么你的!actor.nil?
是这里的原因:
actor = []
actor.nil? #gives you false
!actor.nil? #gives you true
还有!actor_list.include? actor
也给你真
所以你的两个条件都是真的,因此它进入 if 条件并将 [] 附加到你的 actor_list
你可以这样做:
def self.records (producer_id = 0)
actor_list = Array.new
movie_requests(producer_id).find_each do |studio|
actor = studio.actors.pluck(:id).uniq
if actor.present? && (!actor_list.include? actor)
actor_list << actor
end
end
return actor_list
end
那么你将不会得到像这样的任何空白数组[]。
我的代码如下所示:
*movie_requests is a scope
def self.records (producer_id = 0)
actor_list = Array.new
movie_requests(producer_id).find_each do |studio|
actor = studio.actors.pluck(:id).uniq
if (!actor_list.include? actor) && (!actor.nil?)
actor_list << actor
end
end
return actor_list
end
最初在数据库中,它有这些演员 ID:
[[12305], [3749], [1263], [], [], [1263], [], [12305], []]
.pluck 和 .uniq 使每个工作室的冗余 ID 不同,但是 []
仍然存在:
[[12305], [3749], [1263], []]
为什么我的 && (!actor.nil?)
条件没有捕获空 ID 并使其成为一个独特的对象?
Edit:
return actor_list.compact
also doesn't work
您可以检查 actor
是否存在,然后将此 actor
添加到 actor_list
为什么你的!actor.nil?
是这里的原因:
actor = []
actor.nil? #gives you false
!actor.nil? #gives you true
还有!actor_list.include? actor
也给你真
所以你的两个条件都是真的,因此它进入 if 条件并将 [] 附加到你的 actor_list
你可以这样做:
def self.records (producer_id = 0)
actor_list = Array.new
movie_requests(producer_id).find_each do |studio|
actor = studio.actors.pluck(:id).uniq
if actor.present? && (!actor_list.include? actor)
actor_list << actor
end
end
return actor_list
end
那么你将不会得到像这样的任何空白数组[]。