我有兩個表 - 報表和主題。如何在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表中。從一個表,如果我使用的find_by_sql
@student_subject = TermReport.includes(:subject).all
@student_subject = TermReport.joins(:subject).all
然而,這條SQL運行良好的工作平臺,但顯示的數據: 的bolow代碼只從一個表中生成數據。幫助
select * from term_reports t, subjects s
where t.subject_id = s.id
你覆蓋'和'TermReport.joins' TermReport.includes'。 –