SimpleForm required field (*) are not disappear even config at config.wrappers :default - simple-form

I try to config simple_form to always set all fields NOT required by default.
But I still need this when I put :required => true in the view.
Then I go to config/initializers/simple_form.rb and set it like this.
config.wrappers :default, :class => :input, :required => false,
:hint_class => :field_with_hint, :error_class => :field_with_errors do |b|
and set config.required_by_default = false
But asterisk still show up.
Thanks for any suggestion.

Rafaiel,
I had the same problem in Rails 4.0, not sure what you're using.
The best solution I've found is to go to config/locales/simple_form.en.yml and change the first lines like this (the mark: line is the one you change):
en:
simple_form:
"yes": 'Yes'
"no": 'No'
required:
text: 'required'
mark: '' #mark was previously '*', which puts an asterisk in the display!

It's also possible to change SimpleForm setup.
SimpleForm.setup do |config|
# Whether attributes are required by default (or not). Default is true.
config.required_by_default = false
end
Take this into account: (taken from simple form github page)
Required fields are marked with an * prepended to their labels.
By default all inputs are required. When the form object includes
ActiveModel::Validations (which, for example, happens with Active
Record models), fields are required only when there is presence
validation. Otherwise, Simple Form will mark fields as optional. For
performance reasons, this detection is skipped on validations that
make use of conditional options, such as :if and :unless.

Related

How do I validate if my model attribute does NOT match a regex?

I'm using Rails 5. How do I create a validation rule for my model that validset if the attribute does NOT match a pattern? I have this
validates_numericality_of :my_str, :with => /\d:\d/, :allow_blank = true
But what I really want to say is validate if the string does not match the regular expression.
What I have understood is that you want the validation to pass if it's not a number so why dont you change the regex to match anything but numbers:
/^(?!\d)/
Using your code it would be
validates_format_of :my_str, :with => /^(?!\d)/, :allow_blank = true
Or:
as the documentation says
Alternatively, you can require that the specified attribute does not
match the regular expression by using the :without option.
So:
validates_format_of :my_str,format: { without => /\d:\d/}, allow_blank = true
with validates_format_of validates the attributes' values by testing whether they match a given regular expression, which is specified using the :with or :without options

Rails 4 validation message: removes "_id" from message

# model.rb
validates :employee_id, presence: true, uniqueness: true
When left empty, the error message says "Employee can't be blank" when I want it to say "Employee ID can't be blank".
I resolved this by:
# model.rb
validates :employee_id, presence: { message: " ID can't be blank" }, uniqueness: true
which outputs "Employee ID can' be blank".
However, this isn't a really good solution IMO. I would like some means of customizing the entire message, including the attribute prefix.
Is there a simple way to do this?
There are several "correct" ways to go about this, but you definitely shouldn't do it via the validation itself, or by defining your own validation method.
On a model-by-model level, this is controlled by the class-level human_attribute_name method.
If you want your model's employee_id field to be a special case where the _id postfix isn't truncated, define that special case by overridding human_attribute_name:
class MyModel
validates :employee_id, presence: true
def self.human_attribute_name(attr, options = {})
attr == :employee_id ? 'Employee ID' : super
end
end
In broader terms, you can redefine human_attribute_name on ActiveRecord::Base to override handling of all _id attributes, but I doubt you want to do this. Generally, it's a good thing that Rails drops the _id postfix.
The second (and probably better) mechanism is to simply rely on localization. ActiveRecord ties into your locale YAML files for just about everything. If you want your employee_id field to humanize to Employee ID regardless of language, you'll need to edit your YAML files.
# config/locales/en.yml
en:
activerecord:
attributes:
employee_id: "Employee ID"
You can override human_attribute_name and always send default value with id
class MyModel
def self.human_attribute_name(attribute, options = {})
super(attribute, { default: attribute.to_s.humanize(keep_id_suffix: true) } )
end
end
You can write a custom validation. By doing it that way, you get to define the error message inside the validation method.
The relevant section from Rails Guides is here: Performing Custom Validations
Something like:
Class Paystub
validate :employee_id_is_not_blank
def employee_id_is_not_blank
errors[:base] << "Employee must be a part of the record.") if id.blank?
end
end
p = Paystub.create
p.errors.full_messages #=> ["Employee must be a part of the record."]
Section 7.4 in the Rails Guides specified using errors[:base]. Error messages shoveled into :base don't require an attribute to be tied to them.
Update: This is not the right answer. See #meagars answer above.

ThinkingSphinx Order via URL Params

I am using ThinkingSphinx in an application and right now I am not doing any type of order on my results. However, I would like to make this an option via a link someone can click on the page and it just passes it through the URL to 'refresh' the page with the results now ordered.
In the .search parameters I tried doing :order => params[:o] then in the URL passing o=columnname but that does not seem to work.
Just to note, when I hard-code the ordering it works fine, I'm not having trouble with indexing/making a DB column sortable. I would just like to make it so via a URL argument it the results can be displayed ordered.
According to the Sphinx documentation, the fields you want to use for sorting must be flagged as sortable. Attributes defined with has do not have to be flagged, because all attributes are sortable:
class Article
..
define_index do
indexes title, :sortable => true
indexes author(:name), :as => :author, :sortable => true
..
end
Then one can use the :order and :sort_mode parameter to define the sort order:
sort_order = params[:o]
Article.search "pancakes", :order => sort_order, :sort_mode => :desc

Datamapper validations, empty errors

I have a simple model with the following properties:
property :title, String,
:required => true,
:length => 1..200
property :body, String,
:required => true,
:length => 1..200
When I save it (using the save method) with an title that doesn't validate, it won't save, but I get the follow object:
<DataMapper::Validations::ValidationErrors:0x00000003133e10
#resource=#<Pun #id=nil #image="" #title="" #body="dsfsdf" #description=nil
#published=nil #user_id=1 #round_id=nil>, #errors={}>
So the errors hash is empty. However, when it's the body property that's empty, the errors hash detect its problem.
Any idea on why the errors hash is empty when it involves the :title property?
Thanks
So knowtheory wrote in a comment on a blog (in 2010)
that some helper methods were created to compensate for this. His examples for a User model:
User.raise_on_save_failure = true - for all user instances to blow up.
DataMapper.raise_on_save_failure = true
- for EVERYTHING to blow up if it doesn’t save successfully.
Source definitions: dm-core/model.rb and dm-core/resource.rb

Add readable field descriptions to ActiveRecord models

I'd like to add descriptions to ActiveRecord model fields to serve as basic instructions / examples for each of the fields. Basically model metadata. I can then display these in the UI (next to the fields on a form etc.)
The way I'm planning to do it is simply create a static hashtable inside the model with the field name as the key and description as the value. I.e.
FIELD_DESCRIPTIONS = {
'category' => 'Select the category it should appear within.',
'title' => 'The title should be a short but descriptive summary.',
'description' => 'Please enter a full description.'
}
etc.
Then I would create a a basic form helper that would wrap these explanations inside of a span (initially hidden and shown via jQuery) so they could be instatiated via f.field_description(:title) or something along those lines.
Anyone have any better ideas? I'd like to keep this field metadata in the model since many views could use the same information, and I also think it's nice to have descriptions within the model when you're going back to look at the code (like how DataMapper can be used right within the model to specify fields).
To give you a little more detail on what I've already done (and it works fine) here's the code. I think there has to be a prettier way of expressing these descriptions in the model, so let me know if you have any ideas.
In model:
FIELD_DESCRIPTIONS = {
'category' => 'Select the category it should appear within.',
'title' => 'The title should be a short but descriptive summary.',
'description' => 'Please enter a full description.'
}
def self.describe_field(field)
FIELD_DESCRIPTIONS[field]
end
In application_helper.rb
def field_helper(form, field)
"<span class='field_helper'>#{form.object.class.describe_field(field)}</span>"
end
In view:
<%= field_helper(f, 'title') %>
This will produce the desired output:
<span class='field_helper'>The title should be a short but descriptive summary.</span>
UPDATE:
Ok So this is the final code I'm using based on the accepted answer.
File: /config/initializers/describe_attr.rb
if defined?(ActiveRecord)
# let's us add attribute descriptions to each AR model
class ActiveRecord::Base
def self.describe_attr(*params)
attrs = params.shift
unless attrs.nil?
case attrs
when Hash
##attr_descriptions = attrs
when Symbol
return ##attr_descriptions[attrs]
end
end
##attr_descriptions ||= {}
end
end
end
File: /app/models/project.rb
describe_attr(
:category => 'Select the category the project should appear within.',
:title => 'The title should be a short but descriptive summary of the project.',
:description => 'Describe the project in detail.',
:image => 'Upload an image for the project.'
)
File: /app/helpers/application_helper.rb
# assumes you have a style defined for attr_description
def describe_attr(form, attribute)
"<span class='attr_description'>#{form.object.class.describe_attr(attribute)}</span>"
end
File: /app/views/projects/_form.html.erb
<%= describe_attr(f, :title) %>
The hash is a reasonable simple solution, but if you're on rails 2.2 or higher you might want to try the internationalization api to do this. This would also put you in a good place if you ever wanted to add translations.
Check out the i18n guide for details, but basically you would create a config/locales/en.yml that includes your column names like:
en:
labels:
category: Select the category it should appear within.
Then in your view:
<%= t('labels.category') %>
The namespace is your call of course. Also check out section 4.1.4 for a neat way to separate translations based on your current view template.
If you want to patch ActiveRecord, then you can do something like:
# Add this at the bottom of enviroment.rb
class ActiveRecord::Base
def self.field_description(*params)
attrs = params.shift
unless attrs.nil?
case attrs
when Hash
##field_description = attrs
when Symbol
return ##field_description[attrs]
end
end
##field_description ||= {}
end
end
And inside your model you can add this line like a macro:
class Product < ActiveRecord::Base
field_description :category => 'Select the category it should appear within.',:title => 'The title should be a short but descriptive summary.',:description => 'Please enter a full description.'
end
To get the value
Product.field_description : title
You can mix your solution with the label helper itself:
f.label :title, f.describe(:title)
And in your model:
FIELD_DESCRIPTIONS = {
:category => 'Select the category it should appear within.',
:title => 'The title should be a short but descriptive summary.',
:description => 'Please enter a full description.'
}
def describe(:field)
self.class::FIELD_DESCRIPTIONS[field]
end
Be sure to check out formtastic, which includes support for internationalized (or not) field labels as per matschaffer's answer.
http://github.com/justinfrench/formtastic/

Resources