Serialize field is "nil" but does not execute the request "IS NULL"

I have a serialized field in my Project model called ranking.

 serialize :rankings 

Here are a few queries with the results:

 @projects = Project.where("rankings IS NULL") -> 0 results @projects = Project.where("rankings = ?", "") -> 0 results @projects = Project.where("rankings = ?", {}) -> 0 results @projects = Project.where("rankings = ?", "{}") -> 0 results @projects = Project.where("rankings = ?", {}.to_yaml) -> 0 results Project.find(275).rankings -> nil 

This is for a table with 100 threads (of which No. 275 is one). What's happening?

+4
source share
3 answers

Here's the answer.

To request a null with a serialized field in Rails, you should do:

 @projects = Project.where("rankings = ?", nil.to_yaml) 
+3
source

According to this page , Rails serializes things using YAML. Playing with this shows that the results are not necessarily what you expect:

 irb(main):007:0> require 'yaml' => true irb(main):008:0> nil.to_yaml => "--- \n...\n" irb(main):009:0> {}.to_yaml => "--- {}\n" 

I can’t say for sure that this is what you are facing, but it seems like a decent place to start. Hope this helps!

PS: I'm going to assume that using the hash form where will result in the correct request:

 @projects = Project.where(:rankings => nil) 
+2
source

In Rails 4 with Postgres, Rails seems to actually populate the string "null" for serialized columns that are zero.

That is, Rails makes the field display nil , but you must specifically request "null" to get the correct result.

So, under Rails 4, the accepted answer no longer works, but it works for me:

 @projects = Project.where("rankings = 'null'") 
+2
source

Source: https://habr.com/ru/post/1491259/


All Articles