我有两个表 - 报告和主题。如何在 Rails 中一行查询和显示两个表的数据?
关系如下:
class Subject < ActiveRecord::Base
has_many :term_reports
end
class TermReport < ActiveRecord::Base
belongs_to :subject
end
这是模式:
create_table "subjects", force: true do |t|
t.string "name"
t.integer "user_id"
t.date "createdate"
end
create_table "term_reports", force: true do |t|
t.string "student_studentid"
t.integer "subject_id"
t.integer "score"
t.integer "position"
t.integer "term"
t.integer "year"
t.integer "user_id"
t.date "ceatedate"
t.string "remark"
t.string "form_class"
end
现在我要的数据是这样的格式:
Sujectname score position etc..
请注意,主题名称存储在 Sujects 表中。 下面的代码仅从一个表中生成数据:
@student_subject = TermReport.includes(:subject).all
@student_subject = TermReport.joins(:subject).all
但是,此 sql 在 Workbench 中运行良好,但如果我使用 find_by_sql,则显示来自一个表的数据。帮助
select * from term_reports t, subjects s
where t.subject_id = s.id
最佳答案
这应该可以正常工作,您可以在您的控制台上尝试一下:
TermReport.includes(:subject).all.each do |term|
puts "#{term.subject.name} #{term.score} #{term.position}"
end
TermReport.all 就足够了,我认为您不需要 includes(:subject)。
关于mysql - 如何在rails中一行显示多个表中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46807085/