我正在构建一个相当简单的Rails 5应用程序。您可以创建“电影”,然后可以为这些电影创建“评论”。 Rails正在做一些奇怪的事情。我设置了我的应用程序,而不是“新”操作和相应的视图,我有表格在application.html.erb文件中包含的模式中创建新电影。然后我在控制器中为所有电影视图提供@newmovie = Movie.new,因此数据随处可用。
我对电影对象设置的验证如下:
class Movie < ApplicationRecord
has_many :reviews
validates :title, :director, :poster, :synopsis, presence: true
end
当我填写表单以在索引视图的模态中创建新电影并故意将字段留空(以触发验证)时,我明白了:
而不是简单地不接受输入的形式。这里发生了什么?我不能像这样发生这个错误。以前,我有一个“新”的观点。这在先前的设置中没有发生。救命啊!
这是我的整个电影控制器:
class MoviesController < ApplicationController
before_action :find_movie, only: [:show, :edit, :update, :destroy ]
before_action :authenticate_user!, only: [:new, :create, :edit, :update, :destroy]
before_action :find_newmovie, only: [:show, :index, :new, :edit]
def show
@reviews = @movie.reviews.all.order(created_at: :desc).paginate(:page => params[:page], :per_page => 3)
@review = Review.new
if @movie.reviews.blank?
@average_review = 0
else
@average_review = @movie.reviews.average(:rating).round(2)
end
end
def index
@movies = Movie.all.order(title: :asc).paginate(:page => params[:page], :per_page => 3)
@newmovie = Movie.new
end
def new
@movie = Movie.new
end
def create
@movie = Movie.create(movie_params)
@movie.user_id = current_user.id
if @movie.save
flash[:success] = "Your movie was created!"
redirect_to root_path
else
flash[:danger] = "There was a problem with your request"
render :new
end
end
def edit
end
def update
if @movie.update(movie_params)
flash[:success] = "Your movie was updated"
redirect_to movie_path
else
flash[:danger] = "There was a problem with your request"
end
end
def destroy
if @movie.destroy
flash[:success] = "Your movie was removed"
redirect_to movies_path
else
flash[:danger] = "There was a problem with your request"
render :index
end
end
private
def movie_params
params.require(:movie).permit(:title, :director, :poster, :synopsis, :user_id)
end
def find_movie
@movie = Movie.find(params[:id])
end
def find_newmovie
@newmovie = Movie.new
end
end
答案 0 :(得分:0)
在new
的{{1}}行动中,您错过了实例变量movies_controller
的初始化。
在@newmovie
中添加以下代码:
movies_controller