繁体   English   中英

Rails,试图创造一个记录

[英]Rails, trying to create a record

我有几个模型,学生,日记和成绩以及日记条目

每个学生都属于一个年级,每个学生每个年级都有一本日记。

创建学生记录时,选择年级,我希望能够创建带有学生姓名和年级的日记。

日记模型

 class Diary < ApplicationRecord belongs_to :student belongs_to :user belongs_to :grade end

学生模特

 class Student < ApplicationRecord belongs_to :user has_many :diaries, dependent: :destroy has_many :subjects, dependent: :destroy has_many :grades #confusing for me also... should be in one grade at a time? accepts_nested_attributes_for :diaries accepts_nested_attributes_for :subjects def subject_list=(subject_string) subject_name = subject_string.split(“,”).collect{ |s| s.strip.downcase }.uniq new_or_found_subjects = subject_names.collect { |name| Subject.find_or_create_by(name: name) } self.subjects = new_or_found_skills end def subject_list self.subjects.collect do |subject| subject.name end.join(“,”) end end

等级模型

 class Grade < ApplicationRecord has_many :subjects belongs_to :student belongs_to :diary end

学生展示页面

 <div class="col-sm-7"> <div class="card"> <div class="card-body"> <%= simple_form_for :diary, url: new_student_diary_path(@student) do |f| %> <!-- I want to have a button here that creates a diary for the student, without manually entering any information the information shoud be student_id, user_id and student.grade_id --> <%= f.submit "Create Diary", class: "btn btn-primary text-center" %> <%end%> </div>

我的控制器

 def create @student = Student.find(params[:student_id]) @diary = @student.diaries.build(diary_params) @diary.user = current_user respond_to do |format| if @diary.save format.html { redirect_to @diary, notice: 'Diary was successfully created.' } format.json { render :show, status: :created, location: @diary } else format.html { render :new } format.json { render json: @diary.errors, status: :unprocessable_entity } end end end

我的挑战在于模型、控制器和视图......我似乎无法解决这个问题......我真的很感激一步一步的答案,这样我就可以学习如何做到这一点。

根据场景

1 个学生有 1 个日记

1 日记有 1 个等级

所以,

s = Student.new
g = Grade.new
@d = Diary.new(s.id, g.id)

1 学生有多个成绩

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM