ruby-on-rails - 我想在祖父母显示页面下显示孙子记录...我做错了什么?
问题描述
在我的代码中,用户有学生,学生有日记,日记有 diary_entries。我想在学生展示页面下显示每个学生的日记条目。下面是我的模型。
Student.rb 模型
class Student < ApplicationRecord
belongs_to :user
has_many :diaries, dependent: :destroy
has_many :teams, dependent: :destroy
has_many :subjects, dependent: :destroy
belongs_to :grade
accepts_nested_attributes_for :diaries
accepts_nested_attributes_for :subjects
accepts_nested_attributes_for :teams
end
日记.rb模型
class Diary < ApplicationRecord
belongs_to :student
belongs_to :user
belongs_to :grade
has_many :diary_entries
validates :diary_year, presence: true
def self.from_student(owner, student_obj)
new(
user_id: owner.id,
student_id: student_obj.id,
grade_id: student_obj.grade_id,
diary_year: Date.today.year
)
end
end
Diary_entry.rb 模型
class DiaryEntry < ApplicationRecord
belongs_to :diary
belongs_to :subject
belongs_to :user
validates :lesson_date, :assignment, :assignment_due_date, :notes_to_parents, presence: true
end
日记控制器
class DiariesController < ApplicationController
before_action :authenticate_user!
before_action :set_student
def create
@diary = Diary.from_student(current_user, @student)
@diary.save
redirect_to @student, notice: "Diary was successfully created."
end
private
def set_student
@student = Student.find(params[:student_id])
end
end
学生控制器#show
def show
@diary = @student.diaries
@diary_entries = @diary.diary_entries
end
Diary_entries 控制器 #index 和 Show
def index
@diary_entries = @diary.diary_entries.all
end
def show
@diary_entry = DiaryEntry.find(params[:id])
end
我希望每个学生每年只有 1 篇日记,所以我在每个日记中添加了 diary_year 列,然后在日记表上添加了 student_id 和 year 的唯一索引。
create_table "diaries", force: :cascade do |t|
t.bigint "user_id"
t.bigint "student_id"
t.bigint "grade_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "diary_year"
t.index ["grade_id"], name: "index_diaries_on_grade_id"
t.index ["student_id", "diary_year"], name: "index_diaries_on_student_id_and_diary_year", unique: true
t.index ["student_id"], name: "index_diaries_on_student_id"
t.index ["user_id"], name: "index_diaries_on_user_id"
end
下面是我在学生展示页面中尝试的循环。
<div class="card">
<div class="card-body">
<% @diary_entries.each do |entry| %>
<li><%= entry.assignment %></li>
<% end %>
</div>
</div>
我希望能够 1. 让每个学生每年只有 1 篇日记,2. 在每个学生页面下显示 diary_entries。
解决方案
你想展示diary_entries
的Student
,使用joins
@diary_entries = DiaryEntry.joins(diary: :student)
.where(students: { id: @student.id })
更多关于连接 - https://guides.rubyonrails.org/active_record_querying.html#joins
试试看!
推荐阅读
- integer - 两个整数之间的估计操作数(启发式)
- reactjs - 最新版本的刷卡器不工作,说“无法解决'刷卡器'”
- r - 按顺序数字模式匹配列名,并计算所有匹配项的 rowMeans
- c# - VueJs + ASP.Net Core Web API 发出 post 请求
- python - 尝试从 csv 文件绘图时出现索引错误
- python - 列子集上的 df.replace 想要保留完整的数据框
- android - Android StaggeredGridLayoutManager 将不同高度的项目对齐到底部
- arrays - Mule 4 DataWeave 2 数组映射
- excel - 匹配两列并使用 DateTime 验证选择相应的值
- jquery - 检查后需要用最接近 TD 的逗号连接值