Witam,
mam problem z wyswietlaniem komunikatow walidacji modelu Comment.
W widoku ‘games/show’ mam link do formularza w ktorym dodawany jest komentarz przez uzytkownika:
<%= link_to 'Dodaj komentarz', new_game_comment_path(@game), class: 'btn btn-primary btn-lg' %>
Kod formularza komentarzy (comments/_form.html.erb):
<%= form_for [@game, @comment], html: { class: "form-horizontal" } do |f| %>
<% if @comment.errors.any? %>
<%= render 'layouts/errors', object: @comment %>
<% end %>
...
<% end %>
Kod partiala wyswietlajacy komunikaty bledow (layouts/_errors.html.erb):
<% if object.errors.any? %>
<div class="alert fade in alert-danger alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
<ul>
<% object.errors.full_messages.each do |msg| %>
<%= content_tag :li, msg, :id => "error_#{msg}" if msg.is_a?(String) %>
<% end %>
</ul>
</div>
<% end %>
Kontroler (controllers/comments_controller.rb):
class CommentsController < ApplicationController
before_action :set_game, only: [:new, :create]
def new
@comment = Comment.new(parent_id: params[:parent_id])
end
def create
@comment = @game.comments.new(comment_params)
if @comment.save
flash[:success] = 'Twój komentarz został dodany!'
redirect_to game_url(@game)
else
render 'new'
end
end
private
def set_game
@game = Game.friendly.find(params[:game_id])
end
def comment_params
params.require(:comment).permit(:title, :body, :author, :game_id)
end
end
Niestety przy probie dodania komentarza bez wypelniania pol takich jak autor, tresc i tytul nie wyswietlane sa komunikaty walidacji. W konsoli przy probie dodania takiego komentarza pojawiaja sie takie komunikaty:
2.2.0 :005 > comment = Comment.new
=> #<Comment id: nil, title: nil, author: nil, body: nil, created_at: nil, updated_at: nil, game_id: nil, parent_id: nil, user_id: nil>
2.2.0 :006 > comment.save
(0.1ms) begin transaction
(0.1ms) rollback transaction
=> false
2.2.0 :007 > comment.errors.full_messages
=> ["Title nie może być puste", "Author nie może być puste", "Body nie może być puste"]
2.2.0 :008 >
Niestety nie wiem gdzie popelnilem blad. Prosze o pomoc jesli kiedy mieliscie podobny blad.
Model comment.rb
class Comment < ActiveRecord::Base
belongs_to :game
belongs_to :comment
validates :title, :author, :body, presence: true
end