Nothing happened when i run db:seed on Heroku - ruby

My app is made by Sinatra any everything working fine on my local server.
But when i deployed to Heroku and i ran this command
$ heroku run rake db:seed
Nothing happened even this command worked fine.
$ heroku run rake db:migrate
So this is my seed code
require_relative '../app/models/question'
require_relative '../app/models/answer'
require_relative '../app/models/user'
require 'faker'
class TaskSeed
def self.faker
20.times do
Question.create(
:content => Faker::Lorem.sentence(200, true),
:headline => Faker::Lorem.sentence,
:user_id => Faker::Number.between(1, 10)
)
end
40.times do
Answer.create(
:content => Faker::Lorem.sentence(20, true),
:headline => Faker::Lorem.sentence,
:user_id => Faker::Number.between(1, 10),
:question_id => Faker::Number.between(1, 10)
)
end
20.times do
User.create(
:username => Faker::Internet.user_name,
:email => Faker::Internet.email,
:encrypted_password => Faker::Internet.password(10, 20)
)
end
vote_type_arr = ['up','down']
50.times do
QuestionVote.create(
:type => vote_type_arr[rand(0..1)],
:question_id => Faker::Number.between(1, 20)
)
end
end
end
TaskSeed.faker
Anyone know how to fix this?
Thanks!
i am using PostgreSQL as my local since the project was made.

If your local database is clean(no testing data), then you could try heroku db:push
If you are using the default PostgreSQL, try
heroku pg:reset
heroku rake db:seed

Related

bundle exec rake snorby:setup - error rake aborted! invalid hash

While executing below command to setup the snorby on ruby on rails, i get the error: rake aborted! invalid hash. Pls help
#bundle exec rake snorby:setup
#Jammit Warning: Asset compression disabled -- Java unavailable.
No time_zone specified in snorby_config.yml; detected time_zone: Asia/Kolkata
750d6d911891ab576bdbc6b1c4dc5ecf73cb95fd145ab7b16194636094daa3b4ba42b01c05d991c8c174919162e00152a129c645b1e0508850042cf224f165af
mysql: [Warning] Using a password on the command line interface can be insecure.
ERROR 1007 (HY000) at line 1: Can't create database 'snorby'; database exists
[datamapper] Finished auto_upgrade! for :default repository 'snorby'
rake aborted!
invalid hash
Tasks: TOP => db:seed
(See full trace by running task with --trace)
Below are the versions currently used:
#ruby 1.9.3p551 (2014-11-13 revision 48406) [x86_64-linux]
#Bundler version 1.9.3
#Ubuntu 20.04 LTS (focal)
Modifying the entries in seeds.rb file as given below, the error has been resolved. In the seeds.rb changed the line for Default user setup from
User.create(:name => 'Administrator', :email => 'snorby#snorby.org', :password => 'snorby', :password_confirmation => 'snorby', :admin => true) if User.all.blank?
To
User.create(:name => 'Administrator', :email => 'snorby#snorby.org', :encrypted_password => 'snorby', :password_confirmation => 'snorby', :admin => true) if User.all.blank?
i.e the :password was changed to :encrypted_password

rails + heroku: point root in routes.rb file to app.rb file

I have a file called app.rb that runs a server when I run it on my local machine. I would like to deploy app.rb to Heroku so the server will run on Heroku. I think I need to make root in routes.rb point it to. How do I do this?
this is the config.ru:
require_relative 'config/environment'
require '/.app.rb'
run Rails.application
run Sinatra::Application
This is the web server code in app.rb, from codepath guides (https://guides.codepath.com/android/Google-Cloud-Messaging#step-3-setup-web-server):
require 'sinatra'
require 'rest-client'
require 'sequel'
# Create a SQLite3 database
DB = Sequel.connect('sqlite://gcm-test.db')
# Create a Device table if it doesn't exist
DB.create_table? :Device do
primary_key :reg_id
String :user_id
String :reg_token
String :os, :default => 'android'
end
Device = DB[:Device] # create the dataset
# Registration endpoint mapping reg_token to user_id
# POST /register?reg_token=abc&user_id=123
post '/register' do
if Device.filter(:reg_token => params[:reg_token]).count == 0
device = Device.insert(:reg_token => params[:reg_token], :user_id => params[:user_id], :os => 'android')
end
end
# Ennpoint for sending a message to a user
# POST /send?user_id=123&title=hello&body=message
post '/send' do
# Find devices with the corresponding reg_tokens
reg_tokens = Device.filter(:user_id => params[:user_id]).map(:reg_token).to_a
if reg_tokens.count != 0
send_gcm_message(params[:title], params[:body], reg_tokens)
end
end
# Sending logic
# send_gcm_message(["abc", "cdf"])
def send_gcm_message(title, body, reg_tokens)
# Construct JSON payload
post_args = {
# :to field can also be used if there is only 1 reg token to send
:registration_ids => reg_tokens,
:data => {
:title => title,
:body => body,
:anything => "foobar"
}
}
# Send the request with JSON args and headers
RestClient.post 'https://gcm-http.googleapis.com/gcm/send', post_args.to_json,
:Authorization => 'key=' + AUTHORIZE_KEY, :content_type => :json, :accept => :json
end
This is the procfile:
web: bundle exec puma -C config/puma.rb
when I follow the getting started with Ruby on Heroku example, I can see the example webpage. However, if I edit the config.ru file with 'run Sinatra::Application', and deploy to heroku, it is not able to show the example webpage anymore, and just says "Not Found"
require '/.app.rb'
This should be ./app.rb instead.

Set cookie expiration time in Ruby

I am using Ruby with Sinatra do develop a web application.
I have Ruby version 2.3.0, Sinatra 5.0.30
Following the suggestions from Rails cookies, set start date and expire date, I tried this:
#language = 'en-US'
response.set_cookie(:USER_LANGUAGE, :value => #language, :expires => 1.hour.from_now, :domain => '.example.com')
At first I thought it worked because the cookie set except the expiration time is still just only for the session. The error in my Apache error log says this:
NoMethodError - undefined method 'hour' for 1:Fixnum:
Please note: none of these worked to resolve the problem (none of them could be properly found by the compiler)
require 'active_support'
require 'active_support/all'
require 'activesupport'
So, I tried this instead:
#language = 'en-US'
response.set_cookie(:USER_LANGUAGE, :value => #language, :expires => 30, :domain => '.example.com')
Just to see what would happen and nothing changed, it still only expires with the session.
How should I go about setting an expiration time for my cookies in Ruby with Sinatra?
Sinatra doesn't have the ActiveSupport library which provides a helper for number-to-time, so 1.hour.from_now doesn't works here.
You should use this:
class SinatraApp < Sinatra::Base
use Rack::Session::Cookie, :key => 'rack.session',
:domain => 'foo.com',
:path => '/',
:expire_after => 2592000, # In seconds
:secret => 'some_secret'
And set a time in seconds. Because the Sinatra session comes from Rack::Session.
HOW TO ENABLE SESSIONS WITH SINATRA

Issue with Shoes setup

When i am running shoes.rb file, which contains code to install gem, it throws error.
Undefined method setup for Shoes:Class
Code:
Shoes.setup do
gem 'activerecord' # install AR if not found
require 'active_record'
require 'fileutils'
ActiveRecord::Base.establish_connection(
:adapter => 'postgresql',
:dbfile => 'shoes_app'
)
# create the db if not found
unless File.exist?("shoes_app.sqlite3")
ActiveRecord::Schema.define do
create_table :notes do |t|
t.column :message, :string
end
end
end
end
class ShoesApp < Shoes
require 'note'
url '/', :index
def index
para 'Say something...'
flow do
#note = edit_line
button 'OK' do
Note.new(:message => #note.text).save
#note.text = ''
#result.replace get_notes
end
end
#result = para get_notes
end
def get_notes
messages = []
notes = Note.find(:all, :select => 'message')
notes.each do |foo|
messages << foo.message
end
out = messages.join("n")
end
end
Shoes.app :title => 'Notes', :width => 260, :height => 350
The problem was using Shoes4, where the setup method was unimplemented.
Shoes4 now implements Shoes.setup for backwards compatibility reasons but you don't really need it, so it doesn't do anything except for printing a warning that you should rather do gem install gem_name instead of using Shoes.setup.

Tests within Gem need to test migration generator and apply migrations for tests

I'm working on a Gem that contains a migration generator and a bunch of models, classes, etc that utilize the tables created as part of the migration.
Although testing the migration generator itself is easy enough - there's loads of tutorials around for getting that done, what i'm trying to work out is how to actually run the migration on the test DB so I can later test how the gem interacts with the test data?
Since the gem doesn't have a schema.rb, I wasn't sure how to go about doing it.
This is how I run migrations in code;
ActiveRecord::Base.establish_connection(:adapter => "sqlite3", :database => ":memory:")
ActiveRecord::Migration.verbose = false
#migration = Class.new(ActiveRecord::Migration) do
def change
create_table :users, :force => true do |t|
t.string :roles_mask
end
create_table :user_without_roles, :force => true do |t|
t.string :roles_mask
end
create_table :user_without_role_masks, :force => true do |t|
end
end
end
#migration.new.migrate(:up)
If you have a string containing your generated migration you could do something like this in your test setup;
ActiveRecord::Base.establish_connection(:adapter => "sqlite3", :database => ":memory:")
ActiveRecord::Migration.verbose = false
# Or however you intend to grab the output of the migration generator
migration_string = ERB.new(File.read(<file name here>)).result
migration = Class.new(ActiveRecord::Migration)
migration.class_eval(migration_string)
migration.new.migrate(:up)
That should give you a migrated database using the migration you've generated.
You can do something like this:
I am going to assume you're using ActiveRecord. So in your test helper you should setup a in-memory database:
require 'active_record'
# Connection must be establised before anything else
ActiveRecord::Base.establish_connection(
:adapter => defined?(JRUBY_VERSION) ? 'jdbcsqlite3' : 'sqlite3',
:database => ':memory:'
)
Then invoke the rake task within your test. This would look something like:
require 'rake'
requie File.expand_path('../Rakefile', __FILE__) # you'll need to modify this path to actually point to the Rakefile
Rake::Task['db:migrate'].invoke
The rake taks invocation is untested, but that should point you in the right direction.
The other option would be to just run the command:
%x{rake db:migrate}

Resources