I can't populate my data from seed.rb, when I use rake db:seed nothing happens.
Using Rails 5.
Data from Rails 4
Can I use this structure in Rails 5?
Product.delete_all
Product.create!(title: 'CoffeeScript',
description:
%{<p>
CoffeeScript is JavaScript done right. It provides all of JavaScript\'s
functionality wrapped in a cleaner, more succinct syntax. In the first
book on this exciting new language, CoffeeScript guru Trevor Burnham
shows you how to hold onto all the power and flexibility of JavaScript
while writing clearer, cleaner, and safer code.
</p>},
image_url: 'cs.jpg',
price: 36.00)
# . . .
Product.create!(title: 'Programming Ruby 1.9 & 2.0',
description:
%{<p>
Ruby is the fastest growing and most exciting dynamic language
out there. If you need to get working programs delivered fast,
you should add Ruby to your toolbox.
</p>},
image_url: 'ruby.jpg',
price: 49.95)
Product.create!(title: 'Rails Test Prescriptions',
description:
%{<p>
<em>Rails Test Prescriptions</em> is a comprehensive guide to testing
Rails applications, covering Test-Driven Development from both a
theoretical perspective (why to test) and from a practical perspective
(how to test effectively). It covers the core Rails testing tools and
procedures for Rails 2 and Rails 3, and introduces popular add-ons,
including Cucumber, Shoulda, Machinist, Mocha, and Rcov.
</p>},
image_url: 'rtp.jpg',
price: 34.95)
Seed Data Loading and Verifying
Create a test application
$ rails new seedtest
$ cd seedtest
Add product model
$ rails g model product title description image_url price:decimal
$ rails db:migrate
Prepare the db/seeds.rb file
puts 'start loading data'
copy and paste your loading code into db/seeds.rb
puts 'finish loading data'
Load Seed Data
$ rails db:seed
start Loading data
finish Loading data
Verify
$ rails db
sqlite> select * from products;
1|CoffeeScript|
CoffeeScript is JavaScript done right. It provides all of JavaScript's
functionality wrapped in a cleaner, more succinct syntax. In the first
book on this exciting new language, CoffeeScript guru Trevor Burnham
shows you how to hold onto all the power and flexibility of JavaScript
while writing clearer, cleaner, and safer code.
|cs.jpg|36|2017-02-11 10:44:38.648505|2017-02-11 10:44:38.648505
...
...
More data
.exit # when you've finished
Code on github - with commits using each title
Related
I'm new to RoR and jumping into a big RoR project. The project uses a bunch of gems. In fact, the Gemfile.lock file, including dependencies, is 460 lines long. I was told the project went through several different developers, and that there may be a lot of cruft in there.
Is there any way to generate a list of what each gem does? It's not exactly intuitive, especially with names like "capybara" and "cocaine" and "raindrops."
Is there any simple process to determine which gems are required?
You really shouldn't stress too much about what's in the Gemfile.lock at first, just the Gemfile.
To get gem details, I just whipped this little script up to dump summaries of all the gems in your current bundle:
require 'yaml'
gems = `bundle list`
names = gems.scan(/^\s+\*\s+([\w-]+)\s+\(.*\)\s*$/).flatten
names.each do |name|
summary = YAML.parse(`gem spec #{name} summary`).root.value rescue '???'
puts "#{name}: #{summary}"
end
Save it to a file and run it on the command line like so:
ruby whatever-you-saved-it-as.rb
For a project of mine, I got this:
actionmailer: Email composition, delivery, and receiving framework (part of Rails).
actionpack: Web-flow and rendering framework putting the VC in MVC (part of Rails).
actionview: Rendering framework putting the V in MVC (part of Rails).
activemodel: A toolkit for building modeling frameworks (part of Rails).
activerecord: Object-relational mapper framework (part of Rails).
activesupport: A toolkit of support libraries and Ruby core extensions extracted from the Rails framework.
addressable: URI Implementation
annotate: Annotates Rails Models, routes, fixtures, and others based on the database schema.
arel: Arel is a SQL AST manager for Ruby
ast: A library for working with Abstract Syntax Trees.
astrolabe: An object-oriented AST extension for Parser
awesome_print: Pretty print Ruby objects with proper indentation and colors
...
Kinda neat actually.
Assuming that each gem has a meaningful description, you can run something like this from the Rails console:
Gem.loaded_specs.values.map { |g| "#{g.name}: #{g.summary}" }
The dynamic nature of Ruby makes it hard to find unused gems automatically (e.g. through code analysis). However, you can try to remove gems one by one. If your project's test suite passes without a given gem, it is certainly a strong sign that it might be safe to remove it.
I have been using the seedbank gem to give my Rails seeds some structure (i.e. environment specific seed folders, one seed file per model, order dependencies etc.)
Now I came across the seed_fu gem which among other things makes it easy and expressive to say "seed these records, and if one with that id exists, update the other fields". E.g:
Category.seed(:id,
{ :id => 1, :name => "Food" },
{ :id => 2, :name => "Drink" }
)
I can achieve the same result with some cumbersome ActiveRecord calls in my seed files, but I would much rather use the nice syntax provided by seed_fu. Additionally, I want to keep using the features seedbank gives me. Another rationale is that I may migrate only part of my seed files to the other syntax and that it makes no sense to use two rake commands side by side.
If I just put the above code in my db/seeds/categories.seeds.rb file and run rake db:seed:categories i get the error undefined method 'seed'. I guess I would somehow need to import the seed method from SeedFu:ActiveRecordExtension, but I don't know how.
I'm on Rails 3.2.13 and using the newest version of seed_fu straight from the github repo.
Short answer: seed_fu and seedbank work together without any problem.
I was using the zeus gem and hadn't reloaded my Rails environment so the seed_fu DSL just wasn't loaded yet.
(I will leave the question here for anyone wondering if you can use these gems together. TL;DR: yes.)
I need to add rows of test data to my sqlite.
INSERT INTO courses (`name`) VALUES
(‘java'),
(‘ruby').......
How can i do it with rails3?
Thanks
You can write the insert in activerecord way in db/seeds.rb something like:
courses = Course.create([{ :name => 'java' }, { :name => 'ruby' }])
then run rake db:seed.
Fixtures and FactoryGirl are two popular options for adding test data. I'm personally a bigger fan of FactoryGirl because you are working directly with the models in your tests, but it's really a matter of opinion. From my experience, people who use Test::Unit tend to be fans of fixtures, and those who use RSpec tend to like FactoryGirl. This isn't a hard rule though and you will definitely find people who mix them up. It seems to depend on whether you like using DSLs or plain Ruby in your tests.
You can use 'Factory_girl' for creating test objects in your database.
Just install gem and create Factory objects for your project.
this is the link about it
Where and how do I run a simple script that uses my rails environment. Specifically I have one column that holds multiple pieces of information, I've added columns now for each piece of information and need to run a ruby script that can run to call a method on each row of the database to extrapolate data and save it to the new column.
Using a migration sounds like the right way to go if I am understanding your use case.
However, if you really do want to write a standalone script that needs access to your Rails application's models, you can require the environment.rb file from inside your standalone script.
Example:
#!/bin/env ruby
ENV['RAILS_ENV'] = "production" # Set to your desired Rails environment name
require '/path/to/railsapp/config/environment.rb'
# After this point you have access to your models and other classes from your Rails application
model_instance = MyModel.find(7)
model_instance.some_attribute = "new value"
model_instance.save
I have to agree with David here. Use a migration for this. I'm not sure what you want to do, but running it from inside your environment is much, much more efficient then loading up the app environment manually. And since your initial post suggests you're only doing this once, a migration is the way to go:
rails g migration MigrateData
.. generates:
class MigrateData < ActiveRecord::Migration
def self.up
# Your migration code here
end
def self.down
# Rollback scenario
end
end
Of course, you will always want to perform this locally first, using some test data.
Agree with everyone, for this specific case it sounds like migration will be way to go, however, to do this regularly, or write some other task/script that interacts rails app environment make rails generate a rake task for you! This gets saved with your rails app, and can be run again and again :)
Easiest way to generate a rake task that interact with rails app/models is to make Rails generate Rake tasks for you!! :)
Here's an example
run rails g task my_namespace my_task
This will generate a file called lib/tasks/my_namespace.rake which looks like:
namespace :my_namespace do
desc "TODO: Describe your task here"
task :my_task1 => :environment do
#write any ruby code here and also work with your models
puts User.find(1).name
end
end
Run this task with rake my_namespace:my_task
Watch your ruby code task that interacts with rails modal run!
Seeding data:
http://railscasts.com/episodes/179-seed-data
Adding data with migrations
http://railscasts.com/episodes/23-counter-cache-column
Working with Rake Tasks
http://railscasts.com/episodes/66-custom-rake-tasks
I prefer to use migrations for adding some data in your case.
If it's a one-time thing, use a migration.
If this is something that needs to be done multiple times, use a rake task for it.
I'm trying to use fixtures to add more complex test data in order to test specific scenarios with the front-end, which is in Flex. I'm not sure this is the right way to go about it with rails. My rails app is a card game and the 'more complex test data' I'm trying to test are various combinations of cards.
For example, I want to set up a test game where player 1 has cards B and C in hand, where I've specifically added cards B and C to the player's hand in a fixture.
I have basic fixtures for players, games, and users, which have been there for awhile and working fine. I've tried to add the following erb code in the games fixture, to invoke the Game.start method, and am getting
NoMethodError: undefined method `games' for main:Object
The fixture code snippet is :
four:
id: 4
num_players: 3
turn_num: 0
status_id: 1
<% game_four = games(:four).find
game_four.start
%>
game_four = games(:four).find
games method exists only in test cases, not in fixtures.
You should either query the database or use relationships.
This is just an example.
four:
id: 4
num_players: 3
turn_num: 0
status_id: 1
<% Game.find_by_name(four).start %>
Also, this is not really the right place for such command. Fixtures are not intended "to start games".
You should really move this command elsewhere, perhaps in a dedicated test case within the setup block.
EDIT:
I copy here my comment posted a couple of days ago on the original answer with a link to the new Rails Database Seeding feature: http://ryandaigle.com/articles/2009/5/13/what-s-new-in-edge-rails-database-seeding
This is the one explained by Yehuda Katz in his answer and definitely the best way to solve this problem.
Probably the best solution (and in fact, the one that is now canonized on edge) is to have a seeds.rb file in your db directory that you load from a rake task.
Here's what Rails does now on edge (to be in Rails 3).
# db/seeds.rb
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
#
# Examples:
#
# cities = City.create([{ :name => 'Chicago' }, { :name => 'Copenhagen' }])
# Major.create(:name => 'Daley', :city => cities.first)
And then a new rake task (which you can add to your Rakefile):
desc 'Load the seed data from db/seeds.rb'
task :seed => :environment do
seed_file = File.join(Rails.root, 'db', 'seeds.rb')
load(seed_file) if File.exist?(seed_file)
end
If you set up your seeds.rb file this way, you will be following the new convention and will be able to delete the seeds rake task when you upgrade to Rails 3.
Also, migrations are not for data. This is well established and the universal opinion of the Rails core team as far as I know.
If you want to use fixtures method (when loading data for development, not during tests) you can use fixtures_references plugin. Its behaviour will be the same.