为什么连接查询在最后一次返回id为null,即使我没有查询任何类似的id。我应该如何防止这种情况?
2.1.3 :038 > Foo.select('bars.comment_1, bars.comment_2, foos.rating').joins(:bars).each do |b|
2.1.3 :039 > p b.to_json
2.1.3 :040?> end
Foo Load (0.3ms) SELECT comment_1, comment_2, rating FROM `foos` INNER JOIN `bars` ON `bars`.`foo_id` = `foos`.`id`
"{\"comment_1\":\"xyz\",\"comment_2\":\"uvw\",\"rating\":\"good\",\"id\":null}"
"{\"comment_1\":\"xyz\",\"comment_2\":\"uvw\",\"rating\":\"good\",\"id\":null}"
"{\"comment_1\":\"xyz\",\"comment_2\":\"uvw\",\"rating\":\"fair\",\"id\":null}"
"{\"comment_1\":\"xyz\",\"comment_2\":\"uvw\",\"rating\":\"poor\",\"id\":null}"
"{\"comment_1\":\"xyz\",\"comment_2\":\"uvw\",\"rating\":\"good\",\"id\":null}"
答案 0 :(得分:0)
您应该使用only
方法的to_json
选项:
Foo.select('bars.comment_1, bars.comment_2, foos.rating').joins(:bars).each do |b|
p b.to_json(only: [:comment_1, :comment_2, :rating])
end