Why isn't my inclusion validation passing? - ruby

This should be a no brainer. I have a Sinatra application with RSpec and, for some reason, my validations are failing with the inclusion validation.
This is my code:
class Employee < ActiveRecord::Base
validates :department, inclusion: { in: w%(Sales, Finance, Marketing) }
end
This is the spec file:
it 'should save a valid employee' do
employee = Employee.new(name: 'Employee One',
email: 'example#gmail.com',
title: 'Software Engineer',
department: 'Sales')
expect(employee).to be_valid
end
This test fails because the department field is not 'included in the list'. This is aggravating because it fails no matter what field I put. Errors like these are usually from something simple.
What am I missing?

%w is a short-cut for building array of strings. I think you are trying to build an array of strings like this:
["Sales", "Finance", "Marketing"]
In that case the correct form of using %w would be:
%w(Sales Finance Marketing)
See this post for more information on %w syntax in Ruby.
Also, look at the Rails Documentation for inclusion where %w is used correctly.
So, to solve your problem, change your Employee class to look like this:
class Employee < ActiveRecord::Base
validates :department, inclusion: { in: %w(Sales Finance Marketing) }
end

It seems that you have a syntax error, I believe w% should be %w.
Your %w syntax is conflicting with your actual list. The %w makes commas not necessary and actually adds them to your list (which is not what you want). Remove them.
%w(Sales, Finance, Marketing)
=> ["Sales,", "Finance,", "Marketing"]
vs
%w(Sales Finance Marketing)
=> ["Sales", "Finance", "Marketing"]

Related

ruby access to value in sequel response

I have a problem accessing value from Sequel response. It is only my lack of knowledge, I am new to Sequel.
I am writing website where I ask for articles, then I send query for categories (associated with ID in model), so I have 2 variables to iterate.
I do this
#articles.each_with_index do |article, i|
article.id
article.author
...
And I have also value for categories, when I iterate it with pry, I receive good data
#cat.each do |category|
category.each do |c|
puts c
end
end
gives me perfect output with name of the col "category_cz" and value.
So I tried to do upper block and fill in the name of the category in my language.
#articles.each_with_index do |article, i|
article.id
article.author
#cat[i].???.category_cz
end
I don't know how to access values where are ???, I tried combinations based on my associations.
Way I am sending queries.
#articles = Article.association_join(:articles_data_cz).select
binding.pry
#cat = Article.association_join(:category).select(:category_cz)
And I have associations between table Article and Category models.
in category:
one_to_one :articles
in article:
many_to_one :articles_data_cz, key: :article_cz
many_to_one :articles_data_en, key: :article_en
many_to_one :category, key: :category
I know this is my stupidity and lack of knowledge, I tried a lots of combinations and I cannot guess from docs.
Please, any suggestion?
Thanks
M.
I have solved the problem, sequel didn't guess my table name correctly, so I played with associations, now I am accessing all values through the instance of the object of model, and everything works perfectly. For the others, who might be stuck, check the correctness of the association.

How does a YAML double exclamation point work in this i18n gem?

I'm not using Rails and I haven't done any internationalization before, so I'm trying to understand how this particular example works but I'm a little bit stumped:
The r18n-desktop gem reads from a YAML file for translations. Pretty straightforward.
YAML file en.yml:
user:
edit: Edit user
name: User name is %1
count: !!pl
1: There is 1 user
n: There are %1 users
log:
signup: !!gender
male: Он зарегистрировался
female: Она зарегистрировалась
Test ruby code:
require 'r18n-desktop'
R18n.from_env('./localizations/')
R18n::Filters.add('gender') do |translation, config, user|
puts translation
puts config
puts user
translation[user.gender]
end
include R18n::Helpers
class Ayy
attr_accessor :gender
end
girl = Ayy.new
girl.gender = :female
puts t.user.count(5)
puts t.log.signup girl
Output:
There are 5 users
localization-test.rb:13:in
puts: can't convert R18n::Translation to Array (R18n::Translation#to_ary gives R18n::Untranslated) (TypeError) from localization-test.rb:13:in puts' from localization-test.rb:13:in '
Addenum: Looks like the error is in puts rather than the "translation". The actual result of a translation is log.signup[] though so the gender isn't getting through.
What is t.log.signup() expecting?
Seems like you forget to set a filter for !!gender custom type.
R18n has only few built-in filter — like !!pl. Gender filter is not built-in, you need to define it manually.
R18n Filter docs already contains simple filter example for gender:
R18n::Filters.add('gender') do |translation, config, user|
translation[user.gender]
end

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.

ActiveRecord, find by polymorphic attribute

Having this:
class Event < ActiveRecord::Base
belongs_to :historizable, :polymorphic => true
end
user = User.create!
I can:
Event.create!(:historizable => user)
But I can't:
Event.where(:historizable => user)
# Mysql2::Error: Unknown column 'events.historizable' in 'where clause'
I have to do this instead:
Event.where(:historizable_id => user.id, :historizable_type => user.class.name)
Update
Code that reproduces the issue: https://gist.github.com/fguillen/4732177#file-polymorphic_where_test-rb
This has been implemented in Rails master and will be available in
Rails 4. Thanks.
– #carlosantoniodasilva
I do this:
user.events
This is a proper AR query, you can chain it with other scopes and stuff:
user.events.where(<your event conditions here>)
EDIT: AFAIK the other way around you must specify both fields (makes sense: you could have a user with id 4 and another thing with events, like a Party, also with id 4).
EDIT2: Regarding "Why does create work and where doesn't": create is more highlevel than where, because the former deals with "a complete model", while the latter manages things at the database table level.
ActiveRecord's create (AFAIK) uses a combination of new + update_param somewhere down the line.
update_param uses your model's xxxx= methods for assigning each individual property.
In your example, historizable= is a method built by the belongs_to expression. Since the belongs_to "knows" that it's polymorphic, it can deal with the type and id.
On the other hand, when you pass a hash to the where clause, the parameters there only refer to database fields. Rails provides scopes for "higher level" access:
class Event < ActiveRecord::Base
...
scope :by_historizable, lambda { |h| where(:historizable_id => h.id, :historizable_type => h.class.name) }
end
...
Event.by_historizable(user).where(<your other queries here>)
I've heard that this might change in Rails 4, and where might be more "intelligent". But I have not checked yet.
Try:
Event.joins(:historizable).where(:historizable => {:historizable_type => user})

Best practices for status addition in Rails

I need to add status for an object, and need a hint about the Rails way to do this. Somewhere I've seen status was added into the model, but already lost where it was.
By status, I mean something that tracks about the item state. Like {0: :ORDERED, 1: :CHANGED, 2: :SHIPPED, 3: :ARCHIVED} for order in store. Looks like it needs id that stored in DB, constant or symbol that I could use in code instead of integer id, and one or two human readable messages for UI
There's a couple simple ways to do this. If the names of the statuses are short, I'd do basically what Samy suggested and store them directly in the model. So, in your migration, you'd do
add_column :orders, :status, :string
Then, in your model, you can use the status method to retrieve the status. You'll want to make sure you only store valid statuses, so you the :inclusion validator something like this:
class Order
validates :status, inclusion: { in: %w(ordered changed shipped archived) },
presence: true
end
If the statuses are longer, you can do something very much like the above with a short name for each status, then add an additional method to give you the full status message
class Order
STATUSES = { 'ordered' => 'Order placed',
'changed' => 'A change has been made to the order',
'shipped' => 'The order has been shipped',
'archived' => 'The order has been archived' }
def self.valid_statuses
STATUSES.keys
end
validates :status, inclusion: { in: valid_statuses },
presence: true
def extended_status
STATUSES[status]
end
end
If the problem has some complexity (f.e: lots of states, the object changes its behavior when changing its state...), you could use the gem StateMachine.
MagicFieldNames might be what you are looking for, it has a discriminator type column that you can use for Single Table Inheritance.
If you want simpler, you can use a status column which value can equal ordered, changed, or shipped. You don't even need to create constants in Rails or such a thing.

Resources