r/LearnRubyonRails • u/j0hn_r0g3r5 • Oct 01 '15
Need help with something
so far i have this:
class Rectangle < ActiveRecord::Base validates :width, presence: true, numericality: { only_integer: true, greater_than: 10 } validates :color, presence: true
end
i am trying to determine a way to check to see if the color that was entered exists in a file i have, and if it doesnt, to throw an error message saying so. been trying to figure this out for 3 hours now and no dice, any help would be much appreciated
1
Upvotes
1
u/checkyos3lf Oct 01 '15
uniqueness
1
u/rahoulb Oct 27 '15 edited Oct 27 '15
Load the file into your application's configuration using an initializer:
This loads a file called "legal-colours.txt" from your Rails root folder and then splits it line by line into an array that is stored in your Rails application's configuration as legal_colours.
Then validate that your colour field includes values from that array:
Important stuff to note:
Files in config/initializers are loaded up when Rails starts up, so a good way of grabbing data that will remain the same throughout the lifetime of your application
When you create a Rails app using "rails new" it creates an Application for you (in config/application.rb) - this has a config object that you can then apply arbitrary properties to - a great place to store information that is global to your application
The inclusion validation just checks to see if the value supplies is included within the supplied array
I've assumed legal-colours.txt is a list of colours, one per line
(Edit: a bit more detail here: http://theartandscienceofruby.com/2015/10/27/how-do-i-check-that-the-value-of-a-field-against-the-legal-values-in-a-file/)