Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3: How to display error messages in embedded form?

I'm new to rails & trying to set up my first embedded form. The form itself works, but I can't determine how to send validation error messages to the view. I assumed f.object.errors would provide access, but while the method is said to exist, f.object.errors.count always returns 0, and f.object.errors.any? returns false. Apart from not showing the actual error messages, the form is working as expected - that is, failing to insert invalid data and returning to the form which failed validation. Model, controller & view listed below - any help much appreciated.

...
<!-- Form embedded in boards/show.html.erb -->
<%= form_for([@board, @board.boardthreads.build]) do |f| %> 
    <div class="field">  
        <%= f.label :title %><br />  
        <%= f.text_field :title %>  
    </div>  
    <div class="field">    
        <div class="actions">  <%= f.submit %>  </div> 
    </div>
<% end %>
...



class Boardthread < ActiveRecord::Base
  belongs_to :user
  belongs_to :board

  validates :user, :presence => true
  validates :board, :presence => true
  validates :title, :presence => true
end


class BoardthreadsController < ApplicationController
    def create

        @board = Board.find(params[:board_id])
        @boardthread = @board.boardthreads.new(params[:boardthread])  
        @boardthread.user = current_user
        @boardthread.save
        redirect_to board_path(@board) 

    end
end
like image 285
PlankTon Avatar asked Sep 27 '10 11:09

PlankTon


2 Answers

It's because when you failed, you build again an object in your embedded_form. You need use the object with failure in your form.

In your new action you need build your object and use it on your embedded_form. And during your create you use it because it's already define

<%= form_for([@board, @boardthread]) do |f| %>
    <% @boardthread.errors.full_messages.each do |msg| %>
      <p><%= msg %></p>
    <% end %>
    <div class="field">  
        <%= f.label :title %><br />  
        <%= f.text_field :title %>  
    </div>  
    <div class="field">    
        <div class="actions">  <%= f.submit %>  </div> 
    </div>
<% end %>
like image 124
shingara Avatar answered Nov 19 '22 12:11

shingara


In addition to shingara answer: You may also need to add the code to display the errors in your form, someting like

<ul>
  <%-  @boardthread.errors.full_messages.each do |msg| %>
    <li><%= msg %></li>
  <%- end %>
</ul>`
like image 23
Yannis Avatar answered Nov 19 '22 11:11

Yannis