【发布时间】:2020-02-28 14:27:57
【问题描述】:
在我的代码中,用户有学生,学生有日记,日记有 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
我希望每个学生每年只有 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。
【问题讨论】:
标签: ruby-on-rails rails-activerecord