I am adding thousands of entries to my database through seeds.rb and a CSV file. In order to do so I am using Fast_Seeder:
FastSeeder.seed_csv!(Artist, "artist_sample.csv", :name, :sort_name)
I use Friendly-id, and as it is now, it is not creating a slug because I am not feeding it through the file.
How do I go about creating it without having to change the file manually?
Any help would be much appreciated!
I'm not familiar with Fast_Seeder, but I am with friendly-id. Their docs say the following:
# If you're adding FriendlyId to an existing app and need
# to generate slugs for existing users, do this from the
# console, runner, or add a Rake task:
User.find_each(&:save)
It would obviously be more efficient to get friendly-id playing nice in the first place, but barring that you can add that the next line. You basically just need to tap validation. I bet .find_each(&:valid?) might work too. This leads me to wonder if FastSeeder is creating these records without hitting your validations.
EDIT: Yup, I just dug through their source and they are creating straight through the database. You'll probably need to go the route I outlined above.
Related
What is the best possible way to change name of table using migration and change name of all the files like controller, model and associations?
Will there be any issue when someone will try to run rails:db:migrate after cloning my repo?
What is the best possible way to change name of table using migration
To change the name of a table, you can run:
$ rails g migration change_[old_table_name]_to_[new_table_name]
Within the change method in the migration file generated, add this:
def change
rename_table :[old_table_name], :[new_table_name]
end
Change [old_table_name] and [new_table_name] in both cases.
(This part of the question has been answered here.)
will there be any issue when someone will try to run rails db:migrate after cloning my repo?
Nope. Keep the old migration files in place and generate a new one. That's the benefit of database migrations.
What is the best possible way to change name of all the files like controller, model and associations?
It's generally not too big of a deal to change a model name. Many text editors have the ability to search and replace within a directory.
And I would manually rename the filenames.
Here's a set of more detailed steps to make sure you've hit everything that needs to be changed.
I created a Rails model (and controller) with a typo in the name. I renamed all of the files to the correct names, and then I rolled back the migration I used to create the table and changed it to recreate the table with the proper name.
Unfortunately, ActiveRecord still wants to use the old table name, even though it does not appear in any file in my project. I assume it has been cached somewhere but I have no idea where. There are no files in the application's tmp directory that look suspicious.
For the time being, I added a call to "set_table_name" to the model to get around the problem, but I'm really curious about where the old table name is stored and how to get rid of it.
Update: I went ahead and deleted the scaffold using "rails destroy scaffold". When I recreated it (without the typo), it recreated everything with the typo! I know the typo is cached somewhere but I have no idea where.
Rafe - Looks like it could be a bug in Rails. Perhaps you could submit a Rails pull request, or try adding to the config/initializers/inflections.rb file.
have you fixed the class name of your model? rails infers the table name from that
e.g. "class Userr" -> "userrs"
I generally spot typos quite quickly: the first time that the model is mentioned in the console or associations; the controller in the routes.
When I rails generate model urser I just rails destroy model urser and start again.
This just blasts the files away, but it's very convenient and in rails 3 works especially well to destroy every file created by the generator.
If I migrated before spotting the typo I'll let the migration be deleted by the destroy script, let the generate write a new one and then rake db:rollback. That way the urser_table from the previous migration is dropped and the user_table is created.
If there's a bit of code in the files, at that point is mostly in the model or controller itself. I just copy to clipboard the meat of the class before deleting the file and I paste it in the next one.
If there's a lot of code inside various models tests, controllers or helper files: I still use the same approach, but commit it to git before running destroy, so if you something it can always be checked back out.
OK, it turns out that with Rails 3 (and maybe other versions) if you try to generate a model named "Cafe" it will use the name "cave" instead. No idea why.
Here's an example. I duplicated this on different computers, too.
holloway:whatever rafeco$ rails g scaffold Cafe
invoke active_record
create db/migrate/20110412190231_create_caves.rb
create app/models/cafe.rb
invoke test_unit
create test/unit/cafe_test.rb
create test/fixtures/caves.yml
route resources :caves
invoke scaffold_controller
create app/controllers/caves_controller.rb
invoke erb
create app/views/caves
create app/views/caves/index.html.erb
create app/views/caves/edit.html.erb
create app/views/caves/show.html.erb
create app/views/caves/new.html.erb
create app/views/caves/_form.html.erb
invoke test_unit
create test/functional/caves_controller_test.rb
invoke helper
create app/helpers/caves_helper.rb
invoke test_unit
create test/unit/helpers/caves_helper_test.rb
invoke stylesheets
create public/stylesheets/scaffold.css
I have an app that I've converted over from another cms. The old URLs were being stored in the database like so:
/this-is-an-old-permalink/
And I need them to be like this:
this-is-an-old-permalink
Note the absence of forward slashes. What is the easiest way to go about removing them?
I'm not necessarily looking for the exact code to do it (although that'd be nice!) -- I'm asking also as a Rails newb: What is the best method to go about doing things like this? I've only really worked with Rails in setting up a model, controller, views and outputting data. I haven't had to do any processing like this. Would it go in the model? Any help is appreciated!
edit
Do I need to get all records, loop through them, do regex on that one field and then save it?
Since you're likely only going to write this once, your best bet is to create a script for it within lib, or to write a migration for it. I recommend the latter, because it will then be executed automatically with rake db:migrate if you restore from your old backup at a later date. You can then use all your standard Model processing tricks (like you would use on a Controller) within the migration without exposing the substitution code to a Controller.
EDIT:
You can add the following to a new file within lib/tasks to create a new rake task for this called db:substitute_slashes:
namespace :db do
desc "Remove slashes from old-style URLs"
task :substitute_slashes => :environment do
Modelname.find(:all).each do |obj|
obj.fieldname.gsub!(/regex here/,'')
obj.save!
end
end
end
The exclamation on the end of save! means it will throw an exception if the resulting object fails validation, which is a good thing to check for in this case.
You would then be able to execute this with the command rake db:substitute_slashes.
I have a bunch of rails models that I'm re-writing into a single model to simplify my code and reduce unnecessary tables.
I'm wondering what the best way to delete a model class and its table is. I want past migrations to still succeed, but I don't want to leave the empty models lying around.
Do I have to manually delete the old migrations that reference these models, then manually delete the class files?
Does anyone have any tips for the best way to do this?
All in one solution.
Run the following commands:
rails destroy model ModelName
rails g migration DropTableModelName
The former will generate a new migration file which should looks like this:
class DropTableModelName < ActiveRecord::Migration
def change
drop_table :model_name
end
end
Now run db:migrate and you're done.
If you'd like to completely get rid of of a model and its table do this:
rails destroy model Name
The question is a bit stale now, but I just did:
rails destroy scaffold <ModelName> -p
The -p flag shows "pretend" output, which is good for seeing what will happen. Remove the '-p' flag and the results will match the output. This cleaned the entire collection of M-V-C files + testing + js files + the original migration, no problem.
I guess if you are one who likes to hand edit your migrations and include multiple steps in each, losing the original migration could break db:setup, so buyer beware. Keeping one action == one migration file should avoid this potential snafu.
What about doing ruby script/destroy model? That should take care of the model and the migration.
Depending on how far into development or production you are, you may want to migrate the models out safely using a migration to remove/backup data or what not. Then as bobbywilson0 suggested, using
script/destroy model
or if you rspec anything
script/destroy rspec_model
This will remove any spec tests as well.
Or you can always just drag them to the trash folder.
You can take a look at this one at rails guide.
But I suggest, if it is possible, you should delete the models and all references to the models. This will probably save time later as you don't need to maintain the dead code in the codebase.
If you'd rather have a manual based answer:
First run the following command to identify which migrations you want removed:
rake db:migrate:status
Feel free to grep -i on it too if you're confident of your naming scheme.
Make note of all the "add x to model name" and similar alterations to your Model. These can be removed using:
rails d migration AddXToModelName
Do this for every migration besides the initial create migration. The following command will take care of the initial create migration and the files associated with the model:
rails d model ModelName
I'm new to RoR, and I've just used scaffold to generate a table and create the pages for CRUD operations. Now I want to add a new field to this. One place I found tells me how to do that in the database, but is there a way to do it where it will add the field to all the pages too, or is that just a manual operation and I need to make sure I know all my fields up front?
To add a new column to the database
$ script/generate migration add_fieldname_to_tablename fieldname:string
$ rake db:migrate
To get your views up to date you can run the scaffold again, with your updated list of fields. It will balk on replacing your migrations but you can force it to replace your views.
$ script/generate scaffold tablename fieldname:string old_field_1:string ...
At the prompt answer a and it will overwrite the views, but not the old migration. It also won't modify your existing data.
First you'll write a migration to add the field, run the migration, then you need to rerun the scaffold to regenerate the views, etc. Beware, this will wipe out edited files from before. Of course, instead of scaffolding again you could manually add references to new field where appropriate.
You will have to update your database, no matter what (Remember to 'rake db:migrate' after you create the migration!)
Regarding the interface, you are a bit more lucky: the formtastic plugin makes your views look like this:
The 'f.inputs' is calculating the form fields on-the-fly, based on your model's attributes. This will not cover complex forms that need special treatment, but the usual ones, you will get them automatically.
For an easy-to-understand tutorial, see the latest railcast (Railscast #184, you will have to google for it, I can't post 2 links because I'm not cool enough for stackoverflow yet, sorry).
Railcast #185 is supposed to continue covering formtastic, and it's due to be published next monday.
Needs to be done manually, or the scaffold needs to be regenerated.