【问题标题】:rails joins with select returns nil as idrails join with select 返回 nil 作为 id
【发布时间】:2014-11-19 10:58:16
【问题描述】:

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

【问题讨论】:

  • 如果您不选择id 列,您希望它如何正确设置id

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


【解决方案1】:

您应该使用to_json 方法的only 选项:

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

【讨论】:

    猜你喜欢
    • 2012-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多