Validates_format_of? - ruby-on-rails

1 error prohibited this {{model}} from being saved
There were problems with the following fields:
* {{attribute}} {{message}}
I am getting this error and code I am using is:
validates_format_of :user_id , :with => /\A(([0-9]{4})-[A-Z]{2}$)\Z/ , :message => "should be in the format 1111-TT", :allow_nil => true, :allow_blank => true
Any idea what's causing this?

I had this same problem using Rails 2 and i18n 0.5.0. Uninstall i18n 0.5.0 or specify the older version (I'm using 0.4.1) in your environment.

Related

Issue with opening the generated file in MS Excel using axlsx_rails

I am using axlsx_rails in my Rails project to generate an excel file with validations and dropdowns. After generating the File, I tried to open the file in MS Excel and it said that it needs to repair the file and all the validations and dropdowns are cleared off.
Versions
axlsx_rails - 0.1.5
axlsx - 1.3.6
rubyzip - 1.2.0
rails - 4.1.2
ruby - 2.2.2
Code
#excel = Axlsx::Package.new
#excel.workbook.add_worksheet(name: "Samples") do |ws|
ws.add_row #field_names
sheet.add_data_validation("G2:G1000", {
:type => :list,
:formula1 => '"Jim", "Tom", "Jack"',
:showDropDown => false,
:showErrorMessage => true,
:errorTitle => '',
:error => 'Please use the dropdown selector to choose the value',
:errorStyle => :stop,
:showInputMessage => true,
:prompt => 'Choose the value from the dropdown'})
end
#excel.serialize "tmp/SampleTemplate.xlsx"
Sending the file using
send_file "tmp/SampleTemplate.xlsx"
The generated file is working in LibreOffice but not in MSExcel
Please help
Solved. The issue is in the line,
:formula_1 => '"Jim", "Tom","Jack"'
I've changed it to,
:formula_1 => '"Jim, Tom, Jack"'

Rails numericality validation is failing with a Fixnum value

I'm using Ruby 2.2.3 with Rails 4.2.8 and Oracle DB. I have a model called Historico, which has the following validation:
validates :anosemestre, presence: true, numericality: { only_integer: true }
Also, in my schema, I have the correct declaration for the anosemestre column:
t.integer 'anosemestre'
I'm trying to clone an old Historico to a new one by doing somethings like (historico_old is fresh from the DB):
attributes = historico_old.attributes
attributes.delete('id')
historico_novo = Historico.new(attributes)
binding.pry # for debug, obviously
(...)
historico_novo.save
But when I try to save it, the validation fails saying that anosemestre is not a number. When I debug it, I get the following output from pry, which made me even more confused:
[1] pry(Historico)> historico_novo.valid?
=> false
[2] pry(Historico)> historico_novo.errors.messages
=> {:anosemestre=>["is not a number"]}
[3] pry(Historico)> historico_novo.anosemestre
=> 20171
[4] pry(Historico)> historico_novo.anosemestre.class
=> Fixnum
[5] pry(Historico)> historico_novo.anosemestre = historico_novo.anosemestre.to_i
=> 20171
[6] pry(Historico)> historico_novo.anosemestre.class
=> Fixnum
[7] pry(Historico)> historico_novo.valid?
=> true
This issue did not occur in any other model that we have (and we have plenty), and is only happening when I copy the attributes from one historico to another. I have absoloutely no idea how to proceed from here, has anyone else experienced this issue before?

RAILS: undefined method `map' caused by missing I18n translation

I changed the format for a datetime field in a RAILS 4 new.html.erb from :string to datetime and it caused error as below:
undefined method `map' for "translation missing: zh-CN.date.order":String
The view code causing the error above is:
<%= f.input :start_time, :label => t("Start Time"), required: true, :as => :datetime, :ampm => true, :minute_step => 10, :start_year => Date.today.year - 1, :end_year => Date.today.year + 1, :format => 'YYYY/MM/DD/HH/MM', :use_month_numbers => true, :include_blank => true %>
The RAILS source code blows up is in actionview/helpers/date_helper.rb:
def translated_date_order
date_order = I18n.translate(:'date.order', :locale => #options[:locale], :default => [])
date_order = date_order.map { |element| element.to_sym } #<<<<<<===blows up
forbidden_elements = date_order - [:year, :month, :day]
if forbidden_elements.any?
raise StandardError,
"#{#options[:locale]}.date.order only accepts :year, :month and :day"
end
date_order
end
I do have a file zh-CN.yml under /config/locale/ and it is providing translations for others except this one.
UPDATE portion of zh-CN.yml:
zh-CN:
#maint_recordx
Mfg Batches : '订单批次一览'
New Batch : '新批次'
Update Batch : '更新批次'
Edit Batch : '更新批次'
...........
After being bitten by this same error, I found that Rails sets the following key:
:'date.order'
to the value:
["year", "month", "day"]
for the default :en locale
You can confirm this by running the following snippet in rails console for a default rails install:
date_order = I18n.translate(:'date.order', :locale => :en, :default => [])
Notice I just switched #options[:locale] for the default :en value
The rails helper you reference, expects an array for the date_order value, and will blow up if it doesn't get one.
In my case, I improperly configured the I18n::Backend::ActiveRecord gem and therefore it interfered with the value being returned by I18n. You probably have a similar issue preventing the correct value for the :'date.order' key being returned.
EDIT:
In order to fix this, you should probably just need to install the gem 'rails-i18n'. It will handle returning the correct date formats for supported locales. In my case I had a custom configuration in my es.yml locale file that returned an incorrect date format.
Bingo !!! You just have to add the missing key translation to your local translations.
I solved it by adding
en:
date:
order: ["day", "month", "year"]
to
config/locales/en.yml

Gibbon::GibbonError at /visitors You must set an api_key prior to making a call

Running OSX Mavericks, ruby 2.1.1p76 (2014-02-24 revision 45161) [x86_64-darwin13.0], rvm 1.25.23 (master), and rails-4.1.0 (allegedly)
I'm working through the railsapps.org book on learning rails I have finished implementing the mailchimp email list code, and when I press submit on my form, I get the following error:
Gibbon::GibbonError at /visitors
You must set an api_key prior to making a call
I was working through an invalid URI error, and it mysteriously disappeared over the weekend (I haven't touched the Mac since last Friday). Now I have this new error.
My API Key and List ID are valid and properly set. If I look back in the log, I see another error that the mailchimp.lists.subscribe method is missing.
Here's the code as implemented from the book:
class Visitor < ActiveRecord::Base
has_no_table
column :email, :string
validates_presence_of :email
validates_format_of :email, :with => /\A[-a-z0-9_+\.]+\#([-a-z0-9]+\.)+[a-z0-9]{2,4}\z/i
def subscribe
mailchimp = Gibbon::API.new
result = mailchimp.lists.subscribe({
:id => Rails.application.secrets.mailchimp_list_id,
:email => {:email => self.email},
:double_optin => false,
:update_existing => true,
:send_welcome => true
})
Rails.logger.info("Subscribed #{self.email} to MailChimp") if result
end
end
I hate being a noob when I can't debug for myself... Replies are appreciated.
Regards,
Jeff
Gibbon automatically looks for the environment variable MAILCHIMP_API_KEY and Gibbon will use it when you create an instance. If you haven't set a Unix env variable MAILCHIMP_API_KEY, you will need to set it explicitly. To hardcode it:
mailchimp = Gibbon::API.new("your_api_key")
Or obtain it from the config/secrets.yml file:
mailchimp = Gibbon::API.new(Rails.application.secrets.mailchimp_api_key)

Why is this RSpec test failing?

I'm in the process of learning Ruby on Rails, so treat me like a total neophyte, because I am.
I've got a User model with some associated RSpec tests, and the following test fails:
require 'spec_helper'
describe User do
it 'should require a password' do
User.new({:email => 'valid_email#example.com', :password => '', :password_confirmation => ''}).should_not be_valid
end
end
The relevant part of the User model looks like this:
class User < ActiveRecord::Base
...
validates :password, :presence => true,
:confirmation => true,
:length => { :minimum => 6 }
...
end
Here's the catch: if I run User.new(...).valid? from a Rails console using the arguments above, it returns false as expected and shows the correct errors (password is blank).
I was using spork/autotest and I restarted both to no avail, but this test also fails even running it directly with rspec. What am I doing wrong here?
EDIT
I tried a few more things with the test. This fails:
u = User.new({:email => 'valid_email#example.com', :password => '', :password_confirmation => ''})
u.should_not be_valid
So does this:
u = User.new({:email => 'valid_email#example.com', :password => '', :password_confirmation => ''})
u.valid?
u.errors.should_not be_empty
This passes, confirming that :password is indeed blank:
u = User.new({:email => 'valid_email#example.com', :password => '', :password_confirmation => ''})
u.password.should == ''
So, it's actually spork that is causing the problem. You can turn caching off, so that it won't need restarting every time :
http://ablogaboutcode.com/2011/05/09/spork-testing-tip-caching-classes
I think this is what happens :
ruby-1.9.2-p180 :020 > u = User.new
=> #<User id: nil, email: ...
ruby-1.9.2-p180 :021 > u.errors
=> {}
ruby-1.9.2-p180 :022 > u.save
=> false
ruby-1.9.2-p180 :023 > u.errors
=> {:email=>["can't be blank", "can't be blank"], ...}
In short, if you change new to create, it will work :) I think that this happens because the matcher be_valid checks on the model validation errors. There can be a deeper explanation, but i think that if you use create instead of new, it will work.
EDIT : I have a be_valid_verbose version that might help. Just create a 'be_valid_verbose.rb' file in your rspec/custom_matchers folder, and inside it write :
RSpec::Matchers.define :be_valid_verbose do
match do |model|
model.valid?
end
failure_message_for_should do |model|
"#{model.class} expected to be valid but had errors:n #{model.errors.full_messages.join("n ")}"
end
failure_message_for_should_not do |model|
"#{model.class} expected to have errors, but it did not"
end
description do
"be valid"
end
end
Now check against be_valid_verbose instead of be_valid. It will hopefully present you with some more information on what is happening in your case.
As I feared, the answer was stupidity. This was a spork problem. I thought I had killed the existing process and was running rspec independently, but I later found the spork process still running in a different shell, and rspec had been connecting to it all along. Restarting spork (or killing it entirely) and re-running the tests fixed the problem.
I found this particularly deceptive in that rspec continually updated the test output to reflect the fact that it was aware of my test changes, so it appeared to me that it was running against up-to-date code. Now I'm left to wonder what the real utility of spork is, since apparently I can't trust that it's actually running the right tests correctly.

Resources