大家以后有问题,在这个博客后跟帖,我会把问题和相关答案总结之后整合在博客中,供大家查阅。
以下是第五次作业的答案。替换三个文件中的代码即可实现。
This is the homework5 solution, replace the following texts you will see the correct result.
movies_controller.rb
class MoviesController < ApplicationController
def movie_params
params.require(:movie).permit(:title, :rating, :description, :release_date)
end
def show
id = params[:id] # retrieve movie ID from URI route
@movie = Movie.find(id) # look up movie by unique ID
# will render app/views/movies/show.<extension> by default
end
def index
@all_ratings=Movie.ratingcollection
if params[:ratings]
@ratings=params[:ratings].keys
else
@ratings=@all_ratings
end
@movies=Movie.where(rating: @ratings)
@sorted=0
@selectsort="waitparams"
if params[:selectsort]
@selectsort=params[:selectsort]
@movies=@movies.sort_by{|movie| movie[@selectsort]}
if params[:sort].to_i==1
@movies=@movies.reverse
@sorted=0
else
@sorted=1
end
end
end
def new
# default: render 'new' template
end
def create
@movie = Movie.create!(movie_params)
flash[:notice] = "#{@movie.title} was successfully created."
redirect_to movies_path
end
def edit
@movie = Movie.find params[:id]
end
def update
@movie = Movie.find params[:id]
@movie.update_attributes!(movie_params)
flash[:notice] = "#{@movie.title} was successfully updated."
redirect_to movie_path(@movie)
end
def destroy
@movie = Movie.find(params[:id])
@movie.destroy
flash[:notice] = "Movie '#{@movie.title}' deleted."
redirect_to movies_path
end
end
index.html.haml
-# This file is app/views/movies/index.html.haml
%h1 All Movies
= form_tag movies_path, :method => :get do
Include:
- @all_ratings.each do |rating|
= rating
= check_box_tag "ratings[#{rating}]","1",(@ratings.include? rating)
= check_box_tag "ratings[hidden]","1",true,hidden:true
= submit_tag 'Refresh'
%table#movies
%thead
%tr
- if @selectsort=="title"
%th.hilite= link_to "Movie Title",movies_path(:selectsort=>"title",:sort=>@sorted,:ratings=>params[:ratings])
- else
%th= link_to "Movie Title",movies_path(:selectsort=>"title",:sort=>@sorted,:ratings=>params[:ratings])
%th Rating
- if @selectsort=="release_date"
%th.hilite= link_to "Release Date", movies_path(:selectsort=>"release_date",:sort=>@sorted,:ratings=>params[:ratings])
- else
%th= link_to "Release Date", movies_path(:selectsort=>"release_date",:sort=>@sorted,:ratings=>params[:ratings])
%th More Info
%tbody
- @movies.each do |movie|
%tr
%td= movie.title
%td= movie.rating
%td= movie.release_date
%td= link_to "More about #{movie.title}", movie_path(movie)
= link_to 'Add new movie', new_movie_path
movie.rb
class Movie < ActiveRecord::Base
def Movie.ratingcollection
ratingcollect=Array.new
i=0
Movie.select(:rating).distinct.each do |movie|
ratingcollect[i]=movie.rating
i+=1;
end
return ratingcollect.sort
end
end