ActiveRecord加入结果

时间:2017-10-03 08:54:54

标签: ruby-on-rails join activerecord

如果我查看生成的SQL,在RoR中执行ActiveRecord连接似乎有效。 但我无法弄清楚为什么SQL的结果不会返回到变量中。 我正在做的是:

class Book < ActiveRecord::Base
  has_many :readings, dependent: :destroy
  has_many :readers, :through => :readings
  accepts_nested_attributes_for :readings
end

class Reader < ActiveRecord::Base
  has_many :readings, dependent: :destroy
  has_many :books, :through => :readings
  accepts_nested_attributes_for :books
end

class Reading < ActiveRecord::Base
  belongs_to :reader
  belongs_to :book
end

现在,当问:

result = Reading.where(:reader_id => rid, ).joins(:book).select(columns.collect{|c| c[:name]}.join(',')).flatten

它显示正确生成的SQL:

SELECT readings.id,books.title,books.author,readings.when FROM `readings` INNER JOIN `books` ON `books`.`id` = `readings`.`book_id` WHERE `readings`.`reader_id` = 2

但是:结果变量只包含阅读记录的值,而不是连接表的字段。

我错过了什么?

2 个答案:

答案 0 :(得分:0)

我也对协会的变化提出了质疑: -

class Book < ActiveRecord::Base
  has_many :readings, dependent: :destroy
  has_many :readers, :through => :readings
  accepts_nested_attributes_for :readings
end

class Reader < ActiveRecord::Base
  has_many :readings, dependent: :destroy
  has_many :books, :through => :readings
  accepts_nested_attributes_for :books
end

class Reading < ActiveRecord::Base
  belongs_to :reader
  belongs_to :book
end

以这种方式查询: -

reader = Reader.find(rid)
result = reader.books.pluck(:name).join(',')

答案 1 :(得分:0)

最终,我已经重写了我的助手类,并根据需要获取了各个字段。 (建议krishnar) 无论如何:感谢你们的贡献。