How to visualize mandatory fields

Hi,

I'd like to display an input form with some mandatory fields (e.g. with an extra "*"). Some fields aren't mandatory ( so they don't get the "*").
How do I get the information about the field if there's an "validate_presence_of" in the model or not in the view?

TIA,
Martin

I am not totally sure how you would get an extra *
but if you want to outline the field that is mandatory from a
validates_presence_of filter then you need to make sure
your form_for object is the same name as the model
Example:
Say you have a model like this:

class User < ActiveRecord::Base
    validates_presence_of :username
end

Then your form_for object should be something like this:
form_for :user, :url => users_path do |f|
    f.text_field :username
end

and when it fails it will be wrap with a div tag with a class name of
"fieldWithErrors"
and that would end up looking something like this:
<div class="fieldWithErrors"><input id="user_username"
name="user[username]" size="30" type="text" value="" /></div>

then you can just outline it with css any color you want to indicate
that the field is mandatory.
the css would probably end up looking something like this:
.fieldWithErrors>input[type="text"] {
  border:2px solid red;
}

that's the way I do it... I have yet to use the "*" (asterisk) for my
fields.

Martin No wrote:

I'd like to display an input form with some mandatory fields (e.g. with
an extra "*"). Some fields aren't mandatory ( so they don't get the
"*").
How do I get the information about the field if there's an
"validate_presence_of" in the model or not in the view?

You could do something like this:

In your model:

class MyModel < ActiveRecord::Base
  @@mandatory_fields = [ :field1, :field2]
  validates_presence_of *@@mandatory_fields
  def self.mandatory_fields ; @@mandatory_fields ; end

Then in the view, for each field you can do something like:

<%= '*' if MyModel.mandatory_fields.include? :this_field %>
This field: <%= f.text_field :this_field %>

For a reusable solution you could extend ActiveRecord::Base with
something that does the equivalent and create a view helper to use it.
Have a look here for something similar:

http://www.ruby-forum.com/topic/146123

Hi Mark,

You could do something like this:

In your model:

class MyModel < ActiveRecord::Base
  @@mandatory_fields = [ :field1, :field2]
  validates_presence_of *@@mandatory_fields
  def self.mandatory_fields ; @@mandatory_fields ; end

Then in the view, for each field you can do something like:

<%= '*' if MyModel.mandatory_fields.include? :this_field %>
This field: <%= f.text_field :this_field %>

that's what I was looking for. Thanks.

For a reusable solution you could extend ActiveRecord::Base with
something that does the equivalent and create a view helper to use it.
Have a look here for something similar:

http://www.ruby-forum.com/topic/146123

Because I'm new to ruby (and rails) I'll study it and may ask
agains :wink:

Thanks a lot,
Martin