I have application rails and use client_side_validations gem with Devise to validate devise registrations form
//account.rb
has_one :user
validates :username, presence: true, uniqueness: true
//user.rb
belongs_to :account
validates :email, presence: true, uniqueness: true
//new.html.erb
<%= form_for(#user, :url => registration_path(resource_name), :validate => true) do |f| %>
<%= f.fields_for :account, :validate => true do |inner_form|%>
<div class="field">
<%= inner_form.label :username, "Username" %><br />
<%= inner_form.text_field :username %>
</div>
<% end %>
<div class="field">
<%= f.label :email, "Email" %>
<%= f.email_field :email %>
</div>
<div>
<%= f.submit "Sign up" %>
</div>
<% end %>
Validations work fine with email field but for username not worked..
help me,,, thanks
UPDATE ---validate show but this is no nested form
change :account to #account
<%= f.fields_for :account, :validate => true do |inner_form|%>
to
<%= f.fields_for #account, :validate => true do |inner_form|%>
when submit i get the error
Account(#27129348) expected, got ActiveSupport::HashWithIndifferentAccess(#26695068)
when validates not worked, html code
<input id="user_account_attributes_username" name="user[account_attributes][username]" size="30" type="text" data-validate="true">
validates worked
<input id="user_account_username" name="user[account][username]" size="30" type="text" data-validate="true">
issue
user_account_attributes_username
user[account_attributes][username]
worked
user_account_username
user[account][username]
For current DavyJonesLocker/client_side_validations version (Rails 4.2) fixing nested forms is just replacing line (in rails.validations.js or .coffee placed inside validateForm function):
name = name.replace(/\[[\da-z_]+\]\[(\w+)\]$/g, "[][$1]");
With some better regexp, which will eliminate every [ids] and [new_ids] from name string. Here is one solution presented on jeroenj/client_side_validations:
name = name.replace(/\[((?:new_)?\d+|[0-9a-f]{24})\]/g, "[]");
It's nice (as long as you have sane attributes names) but probably there are some better ways to do this. If anyone is good at writing JS regexps please help to improve it. I will try as soon as I finish current project but I'm definitely not a regexp master.
IMPORTANT:
What is more in current client_side_validations version you have to comment out if(...) { } which surrounds mentioned regexp instruction. This is just quickfix, if is probably necessary at some point but I didn't find any usage for it yet.
We found this branch which solved that problem.
I just updated my Gemfile with this line:
gem 'client_side_validations', github: "jeroenj/client_side_validations", :branch => "4-0-deeply-nested-forms"
Hope that work for you
Related
I'm sorry this question might seem silly to advanced but here goes
I am trying to set the Piano type in my form to select the preselected value from the database. It currently brings up the first value instead of the preselected value, this is my form entry for the Piano:
<div class="field">
<%= form.label :Type %><br>
<%= form.select(:Type, options_for_select([['Grand', 'Grand'], ['Upright', 'Upright'], ['Console', 'Console'], ['Spinet', 'Spinet']])) %>
</div>
I have tried adding :selected => Tuning.Type to the form to preselect the entry but it doesn't seem to work.
<div class="field">
<%= form.label :Type %><br>
<%= form.select(:Type, options_for_select([['Grand', 'Grand'], ['Upright', 'Upright'], ['Console', 'Console'], ['Spinet', 'Spinet'], :selected => Tuning.Type])) %>
</div>
I'm a little confused as to whether the select box entries are supposed to be entered in my model or not as this is all new to me and I need help moving forward.
My model reads something like:
class Tuning < ApplicationRecord
validates :Client, presence: true
validates :Tel, presence: true
validates :Address, presence: true
geocoded_by :Address
after_validation :geocode
end
But includes nothing in the way of select values for 'Type', what should I do to show up the preselected type? thank you for your help.
I have tested three ways of doing a field required, first with no gem, just the usual form_for and it did work well, but I need some good gem for making easier adding fields to insert associations, then I installed the Simple Form. Here is the code I am using:
<%= simple_form_for #post do |p| %>
<%= p.text_field :title, :required => true %> <br />
<%= p.input :content, required: true%> <br />
<%= p.input :category_id, input_html: { required: true }%>
<%= p.submit %>
<% end %>
See how I used all the three ways of getting required to true and the usual way of creating a text field of the form_for so I can see if I find a solution. No success. Even after making config.browser_validations = true in config/initializers/simple_form.rb. Why is it working for form_for but not when I am using gems? I also tried Formtastic and had the same issue.
If you place required: true in the input you should see the field has the "required" class and required="required" attribute.
From my understanding, empty form fields saving to database usually defaults to nil (which is what I wanted). But two of my optional form fields are saving as empty ("") instead of nil.
I'm not sure why this is, I've looked at: Understanding Rails validation: what does allow_blank do? and Save blank value as nil in database thinking it may be because I am using allow_blank: true.
My group.rb
# meetup_urlname must be unique
validates :meetup_urlname, uniqueness: { case_sensitive: false, message: "this is already being used by a different group" }, allow_blank: true
# only validate if meetup_apikey or if meetup_urlname is non-empty
validate :url_name_valid?, :if => :meetup_urlname?
validate :api_key_valid?, :if => :meetup_apikey?
_Form.html.erb:
<%= bootstrap_form_for(#group, :html => { :multipart => true }, layout: :horizontal, label_col: "col-sm-3", control_col: "col-sm-9") do |f| %>
...
<h5>Import Events from Meetup</h5>
<div class="field">
<%= f.text_field :meetup_urlname, label: "Meetup Group's URL", type: "text", placeholder: "Enter your Meetup group's url to retrieve your events", prepend: 'http://www.meetup.com/' %>
</div>
<div class="field">
<%= f.text_field :meetup_apikey, label: 'Meetup API Key', placeholder: 'Enter your Meetup API key (Required for advanced meetup functionality)' %>
</div>
<%= f.hidden_field :status %>
<%= f.hidden_field :audit_status %>
<%= f.hidden_field :sref %>
<div class="col-sm-10" style="padding-right: 26px;">
<div class="actions pull-right">
<%= f.submit 'Update Group', class: "action-btn btn-rounded btn-large" %>
</div>
</div>
<% end %>
Is there a way to have the optional form fields save as nil instead of empty by default? Currently have a hack in where if the form field returned empty..it would overwrite as nil.
Any feedback or insight would help. Thanks!
The strip_attributes gem can take care of this for you.
https://github.com/rmm5t/strip_attributes
Could you post more context, please?
With what we've got here, my ideas are:
"" comes from somewhere in the view (please paste it)
Perhaps you're calling somewhere to_s on the :meetup_urlname? nil.to_s will return "" in ruby.
I am very new to Rails and I am facing a somehow weird problem, and my googling didn't helped me so far...
I have implemented a classical CRUD ressource following the Getting Started with Rails guide and I am blocking on the "update" part:
http://guides.rubyonrails.org/getting_started.html#updating-articles
This is part of my model "Devwork":
class Devwork < ActiveRecord::Base
validates :short_title, presence: true, uniqueness: true
validates :title_fr, presence: true, allow_blank: false
translates :title, :summary, :description
globalize_accessors
end
I am using the Globalize gem to persist localized data, and Globalize-accessor for the helpers.
Here is the controller's update action:
class DevworksController < ApplicationController
def update
#devwork = Devwork.find(params[:id])
if #devwork.update(devwork_params)
redirect_to #devwork
else
render :edit
end
end
private
def devwork_params
params.require(:devwork)
.permit!
end
end
And part of the form:
<%= form_for #devwork do |f| %>
<p>
<%= f.label :short_title %>
<%= f.text_field :short_title %>
</p>
<p>
<%= f.label :title_fr %>
<%= f.text_field :title_fr %>
<%= f.label :title_en %>
<%= f.text_field :title_en %>
</p>
<p>
<%= f.submit %>
</p>
<% end %>
short_title and title_fr are mandatory, while there exist another field title_en which is not. I want the update form to be shown again if the update fails (typically because of empty title_fr).
But it doesn't work. The update never fails (never entering render :edit) even if title_fr is empty. In fact, the update does nothing if one of the field is empty, it only updates non-empty fields.
I surely missed something somewhere, but I can't figure it out... perhaps a missuses of Globalize ?
Thanks for your help !
I am having a weird issue with rails form validation. Currently the validation works fine if the form is visible when the page loads but nothing happens if the form is initially hidden and displayed upon user interaction with the page.
Model
class PushNotification < ActiveRecord::Base
belongs_to :application, foreign_key: :appId, primary_key: :appid
validates :message, :presence => true, :length => { maximum: 75 }
validates :max_message_frequency, :presence => true, :numericality => {:only_integer => true, :greater_than => 0}
validates :appId, :presence => true
end
Html Form
<div id="push-message-tab" class="tab-section">
<%= form_for(PushNotification.new,
url: messaging_messaging_cohort_create_push_path(#application, #cohort),
remote: true, validate: true,
html: {
id: :push_notification_create_form,
class: 'new_push_notification_create ' + (#cohort.new_record? ? 'default-segment' : ''),
autocomplete: "off"
}) do |f| %>
<div class="push-form-component-header">
<%= f.label :message, 'Message' %>
<span id="message-char-counter-wrapper"><b id="char-counter">75</b> characters left</span>
</div>
<div class="actions">
<%= f.submit "Save", id:'submit-push', class: 'with-spinner', data: {waiting_text: "Saving"} %>
</div>
<% end %>
</div>
If push-message-tab element is visible when the page loads the rails form validation works great but it doesn't when I specify style="display: none" and toggle the visibility option on the fly. The form will be sent without performing any sort of validation.
I am using rails 3.1 with ruby 1.9.2
Thank you for your support
You seem to be using the client_side_validations gem.
Based on their documentation (https://github.com/bcardarella/client_side_validations) and assuming you are talking about client-side validations I would recommend trying something like this in your javascript:
$('#your_form').resetClientSideValidations();
Just after you set the form as being displayed.