在我的代码中,用户有学生,学生有日记,日记有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
Diary.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
我希望每个学生每年只有一本日记,所以我在每个日记中添加了一个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.让每个学生每年只有一本日记,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
尝试一下!
- 让每个学生每年只有一本日记,
要每年强制执行一个Diary对象,可以在Diary模型中添加一个before_validation。参见Callbacks
回调应调用一个私有函数,该函数检查可能冲突的现有记录。
def ensure_valid_year
return unless student.diaries.where(diary_year: diary_year).any?
# code or function call here to handle rejection of the new Diary object
end
- 在每个学生页面下显示日记条目。
您可以在学生模型中添加另一个关系。
has_many :diary_entries, through: :diaries
您可以这样访问相关的DiaryEntry对象:
student1 = Student.first
student1.diary_entries