Steps to simply Change the Name of my Model - ruby-on-rails

So I think I jacked up my naming conventions (or rather realized I want to do it a different way). I initially created a "Persons" model (which created person.rb). I also created a persons_controller, but apparently rails looks for "People" so I changed the controller name to people_controller.rb (in the files...not in the command line).
I'm new to rails so I really just need to scrap all this and change my names because this setup (having to using Person, Persons, People) throughout the model/controller/views is just a bit confusing for a beginner. All I want to do is change the "Persons" or "People" to the word "Players". So if I were starting from scratch I'd do "rails generate model Player" in the command line, and "rails generate controller Players". But I have no idea how to go about changing my existing controller and model names to this...and I couldn't fully understand some of the older questions related to this topic.
Any help would be greatly appreciated here. Step by Step instruction like your talking to a 12 year old is also highly encouraged given my novice status.
thanks guys,

The basic conventions that will explain everything
About class name and file name
Class name must correspond to file path. In English, if you have a Thing model, it must be in models/thing.rb file ; if you have a ThingsController it must be in controllers/things_controller.rb
Class name with camel case (i.e SomeThing) must be declared in a file with underscore (i.e some_thing.rb). The file name is written in small letters and underscore is used to "separate" the words. Other example: ThisIsEasyToUnderstand will give this_is_easy_to_understand
About model name, table name and controller name
A model name is singular, a table name is plural and a controller is plural. For example a Thing model will have a things table, and will work with a ThingsController controller
Rails try at most to use correct English syntax, so a Person model will work with a people table and a PeopleController controller
You may have trouble when the model name is, in English, the same in its singular and plural form. Ex: aircraft, eyeglasses, scissors etc.. I won't details the solution to keep my answer clear, but know it can append and you can find solutions on those a bit everywhere on internet.
As an overview:
When you create a model, create a name in its singular form
When you create a controller create a name in its plural form
if you need to rename models or controller you already created you must rename in your code but also rename the file name
If you need to rename a model you will also need to rename its table, and you need a migration for that (search google for "rails migration rename table" )
Hope it help for your first steps in Rails

You can quickly scrap a model (and its associated files) by calling
rails destroy model [modelname]
Same with controllers, scaffolds, etc.
rails destroy scaffold [modelname]
rails destroy controller [controllername]
Of course, there's no undoing this after you've deleted them, so I'd create the new controllers/models/scaffolds first, migrate any relevant code, and then destroy the useless files.

Related

What are drawbacks of naming controllers in singular form is Rails?

I know in Rails we follow conventions. And we should name controllers in plural form.
Recently I hired a freelancer to help me with one part of my application in Rails as I'm really new to this framework and ruby.
I had a PortfolioController - this is just feels right because portfolio is a container for entries (who says "I have portfolios"?).
The freelancer said it's not right and I will have troubles not following the convention and renamed it to PortfoliosController. I asked several times what are the exact problems I will have if I name my controller PortfolioController rather than PortfoliosController and I didn't get any explanation other than "You will have problems".
So, can anybody tell me what those problems are?
Well, the simplest reason would be that anyone else who works on that project will probably refer to it in the plural while working on the code, then have to realize "oh, they decided to not follow convention in that one controller" after an unspecified time period of "WTF?" while they try to figure out what they are doing wrong. Also semantically, your controller is a controller of ALL the Portfolios in the Portfolio table.
Code-wise you will have issues with routes. You will have to craft a bunch of non-standard routes because http://my_app/portfolios goes to the index action of the controller by default. You then show a particular portfolio with http://my_app/portfolios/1 which will show you the portfolio with the id of 1. So be prepared to create and maintain a host of custom routes in your config/routes.rb file. You see similar problems with things that have names that are the same whether plural or singular like equipment where you can have one piece of equipment or many pieces of equipment. See this: rails link path and routing error when model singular and plural name are the same (e.g. equipment, species). Not only is it making your routes wonky, it is causing conflicts in methods like portfolio_path or portfolio_url.

composed name of models in rails

I'm working with RoR with a legacy database in spanish language.
I have the table and registropersona and model RegistroPersona. Now I want to run rails generate scaffold_controller registro_persona But the generated name of controller should be
RegistrosPersonasController (Note the final s in Registros and Personas).
How can I do this?
Unfortunately, I don't think there is a way to specify the controller name using scaffold_controller without also affecting the model name. I've looked around and haven't been able to find anything that does what you're looking for.
I believe you have two options:
1 - use rails generate controller RegistrosPersonas. The downside is you end up with a blank controller, and you'd have to fill in all of the REST methods yourself.
2 - use rails generate scaffold_controller RegistrosPersonas. This will create the REST methods for you, however all of the model references will use the pluralized name (ie you'll see RegistrosPersonas.all). So the downside is that you'll need to go through the controller and change each reference from RegistrosPersonas to RegistroPersona. Hopefully you should simply be able to use a simple find + replace in whatever text editor or IDE you're using.
Hope that helps somewhat.
You can either edit your config/initializers/infletions.rb file to support that, or just rename the controller manually.

Ruby/Rails - Models Named with Two Words (Naming Convention Issues)

This is really a question about naming conventions.
I have a model called PromotedEvents
The file is called promoted_events.rb
I created the table with:
create_table :promoted_events do |t|
Now I'm having problems creating anything, so I'm wondering if theres some problem using model with two words
im in the console and tried
a = PromotedEvents.new
a = Promoted_Event.new
a = promoted_event.new
and keep getting a nameerror : uninitialized constant error
Any ideas?
Your class should be singlular.
Name it PromotedEvent in the file promoted_event.rb
a = PromotedEvent.new
Model names are singular and camel case like so pe = PromotedEvent.new()
the file should be promoted_event.rb
Controllers are plural
PromotedEventsController
constants are ALL_CAPS
locals are separated_by_underscores_and_lowercase
table names are plural 'SELECT * FROM promoted_events`
If it helps, I always think of it like this:
The model name is singular because it represents a single, specific thing. So, PromotedEvent is a specific promoted event that has a name, date, etc.
The table name on the other hand is plural. This is because the table stores a collection of these singular items. So, promoted_events.
In rails, filenames are mostly a matter of convention since ruby has pretty lax rules in this regard, but generally it's class_name.rb. This page might help you get a better overview of what conventions are used where and what is specific to Ruby versus Rails.
If you are an extreme rails n00b like me, then you will want to remember to create a class definition for your newly created table and place it in app/models.
It would go like
class LargeCat < ActiveRecord::Base
belongs_to :zoo
end

What kind of information can the Model access in Rails?

In Ryan Bates's first episode on complex forms, he adds the following to a model:
# models/project.rb
has_many :tasks
def task_attributes=(task_attributes)
task_attributes.each do |attributes|
tasks.build(attributes)
end
end
I've never thought about this before, but how does the Project model know what "tasks" of which Project instance? Does that come from the has_many association? Is it like, when the project is running and I'm viewing a Project, that's the "active" object so project.rb knows which Project object we're referring to, so it knows that tasks is really some_current_project.tasks? (I'm obviously grasping at straws here.)
Also, if someone would point me to some reference that explains other questions like this one, I'd really appreciate it.
I hope my question is clear. Please ask for more clarification in comments if needed.
Please note: I know that Active Record handles CRUD actions and that objects correspond to rows in tables, etc. Those are just descriptions of what Active Record is. I'm looking for how it works when the project is running. I also now the constructs MVC, but I can't seem to find a detailed explanation of what information is sent where with respect to Rails.
(Not sure I fully understood your question, feel free to let me know if that's the case.)
A rails model is basically a ruby class that is persisted to a database. So it acts like a normal ruby object for the most part, with some database magic mixed in.
You tell rails which project instance to load (e.g. by providing an id), and it loads the data from the database.
Then, when you call project.tasks is when the magic happens: the Project model has no tasks method, so it will trigger ruby's method_missing method. This will then load the associated records into model instances and provide access to them via a rails object.
Since a project has many tasks, rails knows it should look into the tasks database and load the rows where project_id is equal to the project model's id attribute.
In short, ruby meta-programming and monkey patching possibilities make much of rails' magic possible.
(Edit for question on routing.)
When you want to edit project number 13, you go to a URL that looks something like www.mysite.com/projects/13/edit. If you look at routes.rb in your config directory, you'll see (in Rails3) resources :projects what Rails does is set up all sorts of paths for you. Behind the magic, the edit path looks like
get '/projects/:id/edit' => 'projects#edit'
This basically says "when a user wants to see www.mysite.com/projects/13/edit, send him to the edit action in the projects controller and set the id parameter to the value that's in that place.
Then in your controller, you'll load the appropriate project with
#project = Project.find(params[:id])
In a similar way, you could do this (this is an dumb example):
In routes.rb, put
get '/projects/:id/edit_name/:name' => 'projects#edit'
And then in you controller
#project = Project.find(params[:id])
#project.name = params[:name]
So rails basically uses magic to assign values in the URL to params you can work with in your controller. You can read more about routing here: http://guides.rubyonrails.org/routing.html

custom properties in Rails

I have just started Rails and have a basic question.
I need to add customer properties(like email id etc) so that the Rails app can read them at runtime. How can I do this ?
Can I add them to development.rb and if so how can I read it ?
In java I would have created a properties file and read it from my app.
thank you,
firemonkey
Are you trying to do store and load configuration settings?
It's easy to store configuration settings in a yaml file and load them with initializers - loads better than littering your environment files.
This Railscast: http://railscasts.com/episodes/85-yaml-configuration-file shows you how.
I'm not sure exactly what you are asking. I'm guessing you want an initial set of data in the database that you can access when you actually run the app? If that is so check out this other SO question How (and whether) to populate rails application with initial data
It's a little unclear exactly what you're trying to do, but it sounds like maybe you have a model called Customer and you would like to add some attributes to it, such as email address, id, and so on?
Basically, with Active Record you don't need to do anything special to add a simple attribute (like a string or an integer). Just add a field called "email_address" to your customers table in the database, and all of your Customer objects will automagically get "email_address" and "email_address=" methods (not to mention the Customer class itself getting "find_by_email_address" and other useful methods as well). If you are adding a field containing another model, it's a bit more complicated - add a "something_id" field to the table, and an association to the class definition (eg, "has_one :something"). For more information, see the ActiveRecord api documentation.
You don't have to use any particular means to add the field to your database, but you might want to consider Migrations. Migrations are a convenient way to keep your schema versioned and synchronized across multiple machines.
If you are building your model right now, there's a short cut built in to the generator to add fields. Instead of just saying...
script/generate scaffold customer
...you can say...
script/generate scaffold customer email:string name:string badge_number:integer
...and it will generate all the appropriate fields in your migration, as well as adding them to your generated views.

Resources