rails连接,select返回nil为id

时间:2014-11-19 10:58:17

标签: ruby-on-rails join ruby-on-rails-4

为什么连接查询在最后一次返回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}"

1 个答案:

答案 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