0

所以我在我的应用程序中有一个评论模型,供用户对电影发表评论。我正在为每个单独的电影在 Show 视图中呈现一个新评论的表单。但是,当我尝试提交空白评论以检查错误是否显示在页面上时,它们不会。我可能做错了什么?

我的评论模型:

class Review < ActiveRecord::Base
  attr_accessible :content
  belongs_to :user
  belongs_to :movie

  validates :user_id, presence: true
  validates :movie_id, presence: true
  validates :content, presence: true, length: { maximum: 1000 }

end

我的评论控制器:

class ReviewsController < ApplicationController
  before_filter :signed_in_user, only: [:new, :create, :destroy]

  def new
  end

  def create

    #I'm doing this to get around the mass assignment error.

    movie_id = params[:review].delete(:movie_id)
    @review = current_user.reviews.build(params[:review])
    @review.movie_id = movie_id

    if @review.save
      flash[:success] = "Review created!"
      redirect_to movie_path(@review.movie)
    else
      redirect_to movie_path(@review.movie)
    end
  end

  def destroy
  end
end

我的表格:

<%= form_for(:review, url: reviews_path) do |f| %>

  <%= f.hidden_field :movie_id %>
  <div class="field">
    <%= f.text_area :content, placeholder: "Write a new review..." %>
  </div>
  <%= f.submit "Submit", class: "btn btn-large btn-primary" %>
<% end %>
4

1 回答 1

2

当您从 #create 方法重定向时,您将丢失错误...更改为

if @review.save
  flash[:success] = "Review created!"
  redirect_to movie_path(@review.movie)
else
  render :new
end
于 2012-08-03T16:05:12.670 回答