图书管理员:
class BooksController < ApplicationController
before_action :set_book, only: [:show, :edit, :update, :destroy]
# GET /books
# GET /books.json
def index
if params[:student_id]
student = Student.find(params[:student_id])
@books = student.books
else
@books = Book.all
end
respond_to do |format|
format.html
format.csv {render text: @books.to_csv }
end
end
def show
end
def new
@book = Book.new
end
def edit
end
def create
@book = Book.new(book_params)
respond_to do |format|
if @book.save
format.html { redirect_to @book, notice: 'Book was successfully created.' }
format.json { render :show, status: :created, location: @book }
else
format.html { render :new }
format.json { render json: @book.errors, status: :unprocessable_entity }
end
end
end
def update
respond_to do |format|
if @book.update(book_params)
format.html { redirect_to @book, notice: 'Book was successfully updated.' }
format.json { render :show, status: :ok, location: @book }
else
format.html { render :edit }
format.json { render json: @book.errors, status: :unprocessable_entity }
end
end
end
def destroy
@book.destroy
respond_to do |format|
format.html { redirect_to books_url, notice: 'Book was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_book
@book = Book.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def book_params
params.require(:book).permit(:book_name, :book_level, :total_words, :words_wrong, :self_corrections, :student_id)
end
end
这是我的“学生管理员”
class StudentsController < ApplicationController
def show
@student = Student.find(params[:id]) rescue nil
@books = Book.where(student_id: params[:id])
@book = Book.new
end
def create
student = Student.new(student_parameters)
student.user_id = current_user.id
if student.save
redirect_to student
else
redirect_to 'students#index'
end
end
def index
@students = Student.where("user_id = ?",current_user.id)
@student = Student.new
end
private
def student_parameters
params.require(:student).permit(:first_name, :last_name)
end
end
书籍属于学生,在索引视图中,我显示了个人的学生书籍,我希望页面顶部的标题说“{current student}的书”。我不确定如何拨打当前学生的姓名,我认为我混淆的原因是我正在使用书籍控制器而且student.first_name和student.last_name对我来说无法使用
此外,我想知道在使用学生控制器时如何访问图书数据。例如,当我在本地主持人:3000 /学生/ 2时,我想向所有学生展示书籍。
我正在寻找类似current_student.books或current_student.name的内容,但我不知道如何创建它们。
答案 0 :(得分:1)
而不是......
student = Student.find(params[:student_id])
@books = student.books
...做
@student = Student.find(params[:student_id])
@books = @student.books
这为您提供了可在视图中使用的实例变量@student
,尤其是@student.first_name
和@student.last_name
您可能希望调整视图中的代码,以便仅显示@student
是否为nil(如果未传递params[:student_id]
则为nil。)