I have a couple of simple models that are associated like so:
MODELS
class Task < ActiveRecord::Base
belongs_to :user
validates :name, :presence => true, :message => 'Name cannot be blank, Task not saved'
end
class User < ActiveRecord::Base
has_many :tasks
end
VIEW has a call in it like so:
user.tasks
<– then I loop through the tasks
The Issue:
In the task model —
when I use:
validates :name, :presence => true , :message => 'Name cannot be blank, Task not saved'
I get a 500 error:
ActionView::Template::Error (uninitialized constant User::Task):
NameError in View file
when I use:
validates_presence_of :name
Everything works.
I thought the both validates methods above where the same…is the issue have to do with associations and how validation tie into associated models. I have a hunch that something is going on with the way things are associated, but it is just a hunch.
Any help will be appreciated. Thank very much.
Best Answer
When you use the newer
validates :name
format, you can put multiple validations in one line rather than having to have multiple lines for each type of validation. Because of this, when Rails hits your:message
parameter, it thinks it's a validation method rather than a message associated with:presence
. Try this instead:Also, depending on how you display your errors, this error may actually show up as 'Name Name cannot be....'; if so, you'll want to set the message to just 'cannot be blank, Task not saved'.