ga-wdi-exercises / project2

[project]
1 stars 30 forks source link

Validations & Forms Helpers. Errors not displaying. #912

Closed sanjaywallah closed 7 years ago

sanjaywallah commented 7 years ago

I have the following setup. I went through the Rails guides on validation and form helpers, but I haven't found anything. I also googled the issue, but again, no success.

In my Model:

class Cheerup < ApplicationRecord validates :body, length: {maximum: 170, too_long:"%{count} characters exceeds the maximum 170"} validates :title, length: {minimum: 5, too_short: "%{count} is below the minimum 5 characters"} validates :body, :title, presence: true

has_many :comments belongs_to :user def upvotes self.upvote += 1 end end

In the Controller:

def create @cheerup = Cheerup.new(cheerup_params.merge(user: current_user)) if @cheerup.save flash[:notice] = "Cheerup was created." redirect_to @cheerup else redirect_to new_cheerup_path end end

In the in the view _form.html.erb:

<%= form_for @cheerup do |f| %> <% if @cheerup.errors.any? %>

    errors:

    <% @cheerup.errors.full_messages.each do |message| %>
  • <%= message %>
  • <% end %>

<% end %> <%= f.label :title %> <%= f.text_field :title %> <%= f.label :body %> <%= f.text_area :body %> <%= f.submit %> <% end %>

AndyWhitley commented 7 years ago

Hi Sanjay, a quick reminder that when you are submitting issues, please be sure to add, commit, and push your current code with a "work in progress" commit message and then link the related files / lines from GitHub in the issue. Also, for code that you do paste into an issue, make sure to use backticks ``` to format it.

That that said, your error messages aren't showing because you are redirecting when validation fails instead of simply re-rendering. Try this instead in your create method:

def create
     @cheerup = Cheerup.new(cheerup_params.merge(user: current_user))
     if @cheerup.save
          flash[:notice] = "Cheerup was created."
          redirect_to @cheerup
     else
          render :new 
     end
end
sanjaywallah commented 7 years ago

Hey Andy, thanks. I figured that out last night. That said, I now have another problem, but that's another issue. Thanks.

AndyWhitley commented 7 years ago

No problem. Please open a new issue for the new problem.

sanjaywallah commented 7 years ago

Just solved that one too. Thanks Andy.