user595419
user595419

Reputation:

Why aren't my Active Record validations validating?

So I have a Review model in my app for users leaving reviews for movies. I'm rendering a form for a new Review in the Show view for each individual movie. However, when I try to submit a blank review to check that the errors display on the page, they don't. What could I be doing wrong?

My review model:

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

My reviews controller:

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

My form:

<%= 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 %>

Upvotes: 0

Views: 83

Answers (1)

Jesse Wolgamott
Jesse Wolgamott

Reputation: 40277

When you redirect away from the #create method, you're losing the errors... Change to

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

Upvotes: 2

Related Questions