views:

58

answers:

2

Hi folks,

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
+2  A: 

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 %>
shingara
Ahh - of course! Many thanks shingara.
unclaimedbaggage
A: 

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>`
Yannis
you mix haml and erb :)
shingara
Ah, right! Sorry for that! Now corrected!
Yannis