Forum: Ruby on Rails Newbie:problem when using validates*

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
D81b718e125c403ac8511947ad621333?d=identicon&s=25 antonio rodriguez (Guest)
on 2006-05-18 17:36
(Received via mailing list)
Hi,

I have performed the cookbook tutorial. Before tailoring the views and
controllers, when I put in the model recipe.rb:

validates_uniqueness_of :title
validates_length_of :title, :within => 1...20

And I tried to introduce some new recipe without the above conditions I
got the message:

---------------------------------------------------
New recipe
1 error prohibited this category from being saved

There were problems with the following fields:

     * Name is too short (minimum is 1 characters)

Name
Back
----------------------------------------------------

So, just fine. But after tailoring the views and controller I'm not
longer able to get this, just this one:


  NoMethodError in Recipe#create

Showing app/views/recipe/new.rhtml where line #27 raised:

You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occured while evaluating nil.each

Extracted source (around line #27):

24: <p>
25: <b>Categoria:</b><br/>
26: <select name="recipe[category_id]">
27: <% @categories.each do |category| %>
28: <option value="<%= category.id %>">
29: <%= category.name %>
30: </option>

Why the sentences in the model

Some ideas?

BR

Antonio
--
=====
Por favor, si me mandas correos con copia a varias personas,
pon mi dirección de correo en copia oculta (CCO), para evitar
que acabe en montones de sitios, eliminando mi privacidad,
favoreciendo la propagación de virus y la proliferación del SPAM. Gracias.
-----
If you send me e-mail which has also been sent to several other people,
kindly mark my address as blind-carbon-copy (or BCC), to avoid its
distribution, which affects my privacy, increases the likelihood of
spreading viruses, and leads to more SPAM. Thanks.
=====

--
=====
Por favor, si me mandas correos con copia a varias personas,
pon mi dirección de correo en copia oculta (CCO), para evitar
que acabe en montones de sitios, eliminando mi privacidad,
favoreciendo la propagación de virus y la proliferación del SPAM. Gracias.
-----
If you send me e-mail which has also been sent to several other people,
kindly mark my address as blind-carbon-copy (or BCC), to avoid its
distribution, which affects my privacy, increases the likelihood of
spreading viruses, and leads to more SPAM. Thanks.
=====
4108c0021c64d188494cae8dcfc95fd8?d=identicon&s=25 Jon Mr. (Guest)
on 2006-05-18 17:45
>
>   NoMethodError in Recipe#create
>
> Showing app/views/recipe/new.rhtml where line #27 raised:
>
> You have a nil object when you didn't expect it!
> You might have expected an instance of Array.
> The error occured while evaluating nil.each
>
> Extracted source (around line #27):
>
> 24: <p>
> 25: <b>Categoria:</b><br/>
> 26: <select name="recipe[category_id]">
> 27: <% @categories.each do |category| %>
> 28: <option value="<%= category.id %>">
> 29: <%= category.name %>
> 30: </option>
>
> Why the sentences in the model
>
> Some ideas?
>
> BR
>
> Antonio

Just to be sure.. you did define @categories in your controller right?
something like....


     def new
        @categories = Catgory.find(:all)
     end

if you didn't then you would most definately get that error.

jon
D81b718e125c403ac8511947ad621333?d=identicon&s=25 antonio rodriguez (Guest)
on 2006-05-18 18:21
(Received via mailing list)
> Just to be sure.. you did define @categories in your controller right?
> something like....
>
>
>      def new
>         @categories = Catgory.find(:all)
>      end

Yes I did. Don't know what part of the controller conflicts with the
model. Actually, instead of using 'recipe' I'm using 'article' so the
model article.rb looks:

class Article < ActiveRecord::Base

belongs_to :category
validates_uniqueness_of :title
validates_length_of :title, :within => 1..20

end
---------------------------------------------------------------------------------------------------------
The article_controller.rb is:

class ArticleController < ApplicationController

         scaffold :article

         def index
             list
             render_action 'list'
         end

         def list
                 @category = @params['category']
                 @articles = Article.find_all
         end

         def edit
                 @article = Article.find(@params["id"])
                 @categories = Category.find_all
         end

         def new
                 @article = Article.new
                 @categories = Category.find_all
         end

         def create
                 @article = Article.new(@params['article'])
                 @article.created = Date.today
                 if @article.save
                         redirect_to :action => 'list'
                 else
                         render_action 'new'
                 end
         end

         def delete
                 Article.find(@params['id']).destroy
                 redirect_to :action => 'list'
	end
end
----------------------------------------------------------------------------------------------------
And the view for a new article is new.rhtml:

<html>

<head>
<title>Nuevo Articulo</title>
</head>

<body BGCOLOR="#99ccff">

<h1>Nuevo Articulo</h1>

<form action="/article/create" method="post">

<p>
<b>Titulo</b><br/>
<input id="article_title" name="article[title]" size="30" type="text"
value=""/>
</p>

<p>
<b>Descripcion</b><br/>
<input id="article_description" name="article[description]"
size="30" type="text" value=""/>
</p>

<p>
<b>Categoria:</b><br/>
<select name="article[category_id]">
<% @categories.each do |category| %>
<option value="<%= category.id %>">
<%= category.name %>
</option>

<% end %>
</select>

</p>

<input type="submit" value="Crear"/>
</form>
<a href="/article/list">Volver</a>
</body>
</html
----------------------------------------------------------------------------------------------------

Any idea?

Cheers

Antonio




>
> if you didn't then you would most definately get that error.
>
> jon
>
>


--
=====
Por favor, si me mandas correos con copia a varias personas,
pon mi dirección de correo en copia oculta (CCO), para evitar
que acabe en montones de sitios, eliminando mi privacidad,
favoreciendo la propagación de virus y la proliferación del SPAM.
Gracias.
-----
If you send me e-mail which has also been sent to several other people,
kindly mark my address as blind-carbon-copy (or BCC), to avoid its
distribution, which affects my privacy, increases the likelihood of
spreading viruses, and leads to more SPAM. Thanks.
=====
6a657bbaaa704aa1fc7dfa6d680c06fc?d=identicon&s=25 Phillip Novess (Guest)
on 2006-05-18 18:31
(Received via mailing list)
I recently had this very same problem using collection_select.

The problem lies in that the create method does not actually run the
new method on error.  So what happens is category is null when your
validation fails.

You have to do a find for your categories in the create method as
well. Like so:

       def create
                 @article = Article.new(@params['article'])
                 @article.created = Date.today
                 if @article.save
                         redirect_to :action => 'list'
                 else
			@categories = Category.find_all
                         render_action 'new'
                 end
         end


I posed the question that this seems to defeat the DRY methodology? I
personally do not know Ruby well enough to identify maybe a better way.

Thanks,
Phill
D81b718e125c403ac8511947ad621333?d=identicon&s=25 antonio rodriguez (Guest)
on 2006-05-18 21:27
(Received via mailing list)
Phillip Novess
escribió:>                 @article = Article.new(@params['article'])
>                 @article.created = Date.today
>                 if @article.save
>                         redirect_to :action => 'list'
>                 else
> 			  @categories = Category.find_all
>                         render_action 'new'
>                 end
>         end
>
>

Getting better

Now I do not have any message. The 'New article' template does nothing
just waits for the right insert. But doesn't alert me about duplicate or
empty fields.

Cheers,

Antonio

=====
Por favor, si me mandas correos con copia a varias personas,
pon mi dirección de correo en copia oculta (CCO), para evitar
que acabe en montones de sitios, eliminando mi privacidad,
favoreciendo la propagación de virus y la proliferación del SPAM. Gracias.
-----
If you send me e-mail which has also been sent to several other people,
kindly mark my address as blind-carbon-copy (or BCC), to avoid its
distribution, which affects my privacy, increases the likelihood of
spreading viruses, and leads to more SPAM. Thanks.
=====
6a657bbaaa704aa1fc7dfa6d680c06fc?d=identicon&s=25 Phillip Novess (Guest)
on 2006-05-18 21:36
(Received via mailing list)
Does your view have a place to display errors?  Such as:

  <%= error_messages_for 'articles' %>


Also I noticed you still have

scaffold :article

in your controller.  You may want to copy your controller code you
have so far and rebuild using

 > ./script/generate scaffold ModelName ControllerName

at the command line.  Then merge your changes.  The scaffold call in
your controller may be interfering with your methods in your controller.

I had to add the find code to all form methods in my controller -
edit, new, create, and update.  Your update method must be coming
from your  scaffold :article line.


Thanks,
phill
4108c0021c64d188494cae8dcfc95fd8?d=identicon&s=25 Jon Mr (jon-d)
on 2006-05-19 15:56
>
> Also I noticed you still have
>
> scaffold :article
>
> in your controller.  You may want to copy your controller code you
> have so far and rebuild using
>
>  > ./script/generate scaffold ModelName ControllerName
>
>
> Thanks,
> phill


I agree! that was the first thing i noticed about all that code. i've
never had a problem with a scaffold before.


Jon
This topic is locked and can not be replied to.