Migration files in Rails - ruby-on-rails-3

I am creating a model in rails (3.2.3) and am defining what columns are to be included (hope thats correct)
for example my first entry is
t.string :Dish_Name
My first question is can I use that syntax i.e. Dish_Name ?
My second question is I want to use dropdowns to select options from the input field, so for exampel i would like to have a "Country of origin" with multiple options, countries of the world.
Would it be better to have a separate DB with all the countries in and then pull in the data from the dropdown? If so could someone point me in the right direction to see how to do this? not necessarily looking for the answer just a good place to start looking
Thanks

Leading uppercase names are reserved for constants. Typical column names are lowercase with underscores (e.g. dish_name or country_of_origin). These are Ruby conventions, and Rails follows along. Naming conventions matter in Ruby, unlike a language like C#, where you call anything just about anything with any casing you want.
Be sure to check out guides.rubyonrails.org for a lot more information.

Related

Custom, user-definable "wildcard" constants in SQL database search -- possible?

My client is making database searches using a django webapp that I've written. The query sends a regex search to the database and outputs the results.
Because the regex searches can be pretty long and unintuitive, the client has asked for certain custom "wildcards" to be created for the regex searches. For example.
Ω := [^aeiou] (all non-vowels)
etc.
This could be achieved with a simple permanent string substitution in the query, something like
query = query.replace("Ω", "[^aeiou]")
for all the elements in the substitution list. This seems like it should be safe, but I'm not really sure.
He has also asked that it be possible for the user to define custom wildcards for their searches on the fly. So that there would be some other input box where a user could define
∫ := some other regex
And to store them you might create a model
class RegexWildcard(models.Model):
symbol = ...
replacement = ...
I'm personally a bit wary of this, because it does not seem to add a whole lot of functionality, but does seem to add a lot of complexity and potential problems to the code. Clients can now write their queries to a db. Can they overwrite each other's symbols?
That I haven't seen this done anywhere before also makes me kind of wary of the idea.
Is this possible? Desirable? A great idea? A terrible idea? Resources and any guidance appreciated.
Well, you're getting paid by the hour....
I don't see how involving the Greek alphabet is to anyone's advantage. If the queries are stored anywhere, everyone approaching the system would have to learn the new syntax to understand them. Plus, there's the problem of how to type the special symbols.
If the client creates complex regular expressions they'd like to be able to reuse, that's understandable. Your application could maintain a list of such expressions that the user could add to and choose from. Notionally, the user would "click on" an expression, and it would be inserted into the query.
The saved expressions could have user-defined names, to make them easier to remember and refer to. And you could define a syntax that referenced them, something otherwise invalid in SQL, such as ::name. Before submitting the query to the DBMS, you substitute the regex for the name.
You still have the problem of choosing good names, and training.
To prevent malformed SQL, I imagine you'll want to ensure the regex is valid. You wouldn't want your system to store a ; drop table CUSTOMERS; as a "regular expression"! You'll either have to validate the expression or, if you can, treat the regex as data in a parameterized query.
The real question to me, though, is why you're in the vicinity of standardized regex queries. That need suggests a database design issue: it suggests the column being queried is composed of composite data, and should be represented as multiple columns that can be queried directly, without using regular expressions.

Underscores or camelCase in PostgreSQL identifiers, when the programming language uses camelCase?

This has been bothering me for a while, and I can't arrive at a solution that feels right...
Given an OO language in which the usual naming convention for object properties is camelCased, and an example object like this:
{
id: 667,
firstName: "Vladimir",
lastName: "Horowitz",
canPlayPiano: true
}
How should I model this structure in a PostgreSQL table?
There are three main options:
unquoted camelCase column names
quoted camelCase column names
unquoted (lowercase) names with underscores
They each have their drawbacks:
Unquoted identifiers automatically fold to lowercase. This means that you can create a table with a canPlayPiano column, but the mixed case never reaches the database. When you inspect the table, the column will always show up as canplaypiano - in psql, pgadmin, explain results, error messages, everything.
Quoted identifiers keep their case, but once you create them like that, you will always have to quote them. IOW, if you create a table with a "canPlayPiano" column, a SELECT canPlayPiano ... will fail. This adds a lot of unnecessary noise to all SQL statements.
Lowercase names with underscores are unambiguous, but they don't map well to the names that the application language is using. You will have to remember to use different names for storage (can_play_piano) and for code (canPlayPiano). It also prevents certain types of code automation, where properties and DB columns need to be named the same.
So I'm caught between a rock and a hard place (and a large stone; there are three options). Whatever I do, some part is going to feel awkward. For the last 10 years or so, I've been using option 3, but I keep hoping there would be a better solution.
I'm grateful for any advice you might have.
PS: I do realize where the case folding and the need for quotes is coming from - the SQL standard, or rather PostgreSQL's adaptation of the standard. I know how it works; I'm more interested in advice about best practices than explanations about how PG handles identifiers.
If your columns in the PostgreSQL are with underscores, you can put aliases but with doule-quotes.
Example :
SELECT my_column as "myColumn" from table;
Given that PostgreSQL uses case-insensitive identifiers with underscores, should you change all your identifiers in your application to do the same? Clearly not. So why do you think the reverse is a reasonable choice?
The convention in PostgreSQL has come about through a mix of standards compliance and long-term experience of its users. Stick with it.
If translating between column-names and identifiers gets tedious, have the computer do it - they're good at things like that. I'm guessing almost all of the 9-million database abstraction libraries out there can do that. If you have a dynamic language it'll take you all of two lines of code to swap column-names to identifiers in CamelCase.
I know this is late however for something that would be simple to translate on the fly, you could write a small help function that would live in your code as such:
function FormatObjForDb(srcObj){
const newObj = {};
Object.keys(srcObj).forEach(key => newObj[key.toLowerCase()] = srcObj[key]);
return newObj;
}
export const formatObjForDb = FormatObjForDb;

Simple Natural Language Parser in Objective-C

I'm building this app for Mac OS X v10.6
I'm building a text-based adventure and I've created a very simple natural language parser that can process the commands that the user types. So far it works great and can parse sentences such as: "take the sword" or "look in the box"
What I'm trying to do is create a list of aliases for different words to make typing commands less strict. So for example "take" could have an alias of "grab" or "go" could have the aliases "move, walk, or travel"
I've tried creating an NSDictionary where the key was the word and the value was an NSArray of aliases. The problem was that when determining if the command entered matched an available command, I would have to reference the aliases with the word that was used for the key.
I want to be able to use any of the aliases to reference any of the other aliases. Does anyone know of a good way to do that?
Another thought I had (but it seems to inefficient) is to store each set of aliases in an array. When parsing I would find the array that contains the word I want to match and try to match all the other words in that array against it.
Check NSLinguisticTagger class (new in iOS 5)
Conceptually, I think you might find it productive to treat all words on the same footing. Let your dictionary have any word from your vocab as a key, and the value numerically encode the interpretation or information that guides interpretation in context.
It works also for OS X http://cutecoder.org/programming/introduction-cocoa-nslinguistictagger-nsbrief-podcast-72/ and check out https://github.com/adib/ColorizeWords

variable naming conventions for when desired name is already defined

Is there a convention for naming a variable when the name you want is already defined by the language? As an example, I'm currently coding a lisp function that takes two parameters, min and max. Vim's syntax highlighter colors those words though, so it looks like they're already lisp functions. I assume it'd be better to give the parameters different names.
Should I use completely different names? min and max are both short and descriptive though, so I'd like to use them if possible. Should I use a prefix, like myMin and myMax? I'm currently leaning towards that idea. Any suggestions would be helpful.
If you are looking for a very general naming convention - the one that would work well with all names reserved/defined in your language or framework - I really doubt that such convention would be practical or even useful.
I think you should do it on a (common) case by case basis.
Your example looks like one of such common cases: it probably is quite common for functions to have two parameters specifying some range of values. Well, in that case, I'd probably go with names like minValue and maxValue - they seem to be abstract enough to work well in most situations.
BTW, I would not use a prefix like my. However, if you were open to the idea of Apps Hungarian (see discussion on Wikipedia and Joel Spolsky's article), the answer to your question would be much simpler: just use a proper semantic prefix in the names of your parameters (e.g. xMin and xMax for min and max abscissa values).

not on a query in RoR

In Ruby on rails 3 I want to query on a has_many field of a model as follows:
#project.items.where(:status => 1)
The problem is I'm trying to get the exact opposite result than this. What i want is all items of #project where the status is not 1. Been looking for the answer to this for a while, anyone?
There are many ways to accomplish what you are trying to do, however, some are better than others. If you will always be searching for a hardcoded number (i.e. 1 in this case), then the following solution will work:
#project.items.where('status != 1')
However, if this value is not hard-coded, you are openly vulnerable to SQL injection as Rails will not (cannot) escape this kind of query. As a result, it is preferred among Rails developers to user the following syntax for most custom conditions (those that can't be constructed via Hash):
#project.items.where(['status != ?', 1])
This syntax is slightly confusing, so let me go over it. Basically you are providing the where clause an Array of values. The first value in the array is a String representing the query you want executed. Anywhere you want a value in that string, you place a ?. This serves as a placeholder. Next, you add an element for every question mark in you query. For example, if I had the following:
where(['first_name = ? AND last_name = ?', params[:first_name], params[:last_name]]
Rails will automatically match these up forming the query for you. In that process, it also escapes potentially unsafe characters, preventing injection.
In general, it is preferred to use the Array syntax, even for a hardcoded value. I've been told that pure string conditions in Rails 3.5 will raise a warning (unverified), so it doesn't hurt to get in the process of using the Array syntax now.