The code below, stored at config/initializers/console.rb works only at first time I exec rails console CLI. When exit and enter again, no selection message is displayed, but the preview tenant selected is loaded.
if defined?(Rails::Console) || $PROGRAM_NAME.include?('spring')
tenants = Apartment.tenant_names.sort
default = tenants.first
puts "Available tenants: #{tenants.join(', ')}"
print "Select tenant (#{default}): "
tenant = gets.strip
Apartment::Tenant.switch! tenants.include?(tenant) ? tenant : default
end
I wish every time when enter at rails console ask for what tenant will be loaded.
Thanks!
The only way I could get Apartment::Tenant.switch! to work in the Rails console was by creating the following .irbrc file in the project's root directory:
IRB.conf[:IRB_RC] = Proc.new do
tenants = Apartment.tenant_names.sort
puts "Available tenants: #{tenants.join(', ')}"
print "Select tenant: "
tenant = gets.strip
unless tenant.empty?
if tenants.include?(tenant)
Apartment::Tenant.switch!(tenant)
else
puts "Tenant not found in list '#{tenant}'"
end
end
puts "Tenant set to '#{Apartment::Tenant.current}'"
end
I faced similar issue. If you are using the Apartment Gem. In your rails console you can switch between tenants by first connecting to DB and then using schema_search_path
e.g.
c = Company.connection
c.schema_search_path = "tenant1"
To check tenant has been switched use ActiveRecord::Base.connection.schema_search_path
=> "\"tenant1\""
Company is just a table in my DB.
Here is a simple code (pry version) usable at launch or while at console
`Apartment::Tenant.switch!` during `bin/rails console` using `pry`
This happens because of Spring, by default it's configured only for the development environment. Just remove it from your Gemfile and it should work as you expected.
Related
Hey we are 3 students, we all use the same rails db:seed. Our project is well git pulled and coordinated, but ..
One uses Linux, the rails:db:seed works for him.
One uses Mac, the rails:db:seed works for him too.
Me, I use WSL, and it dosnt work !
I've tried both Windows & WSL paths, as the screens bellow.
Thanks if anyone can guide me !
config/seed.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 bin/rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Character.create(name: 'Luke', movie: movies.first)
require 'faker'
RealEstate.destroy_all
User.destroy_all
Category.destroy_all
Category.create(title:"House")
Category.create(title:"Flat")
10.times do
u = User.create(email: Faker::Internet.email, password: Faker::Internet.password)
end
30.times do
re = RealEstate.create(
title: Faker::Space.galaxy,
description: Faker::Lorem.paragraph_by_chars(number: 256),
address: Faker::Address.full_address,
location: Faker::Address.city,
price: Faker::Number.number(digits: 8),
user: User.all.sample(),
category: Category.all.sample()
)
re.images.attach(io: File.open(ENV['SAMPLE_IMAGES']), filename: 'sample_image')
end
puts "%" * 50
puts " Base de données remplie !"
puts "%" * 50
Resolved !
I actually went to the folder where the file was stocked and simply typed " pwd " :
So, in my case the pathname was : '/home/pedrofromperu/next/images/indian.jpg'
This issue you are experiencing happens to lots of people who switch between Unix-Like and Windows operating systems. Paths in Windows are written using ‘\’ instead of ‘/‘. This is particularly confusing when using WSL and PowerShell in windows terminal - you have to keep track of which shell environment you are using. Congrats using ‘print working directory’, pwd, to solve the problem.
One thing you could do if you change environments a lot, (and this is just one approach.) Use the OS gem like so:
require 'os'
OS.windows? # returns true or false.
You could then either provide different paths or get fancy and replace the characters in your string.
I have 2 databases defined in my YAML: primary and datawarehouse.
With the following code:
pp ActiveRecord::Base.connection_config
ActiveRecord::Base.connected_to(database: :datawarehouse) do
ActiveRecord::Base.connection.execute('select 1')
end
pp ActiveRecord::Base.connection_config
I would expect the output to be the same before and after the block and let it get back to the default.
However the output before gives me:
=> {:adapter=>"postgresql", :host=>"postgres", :encoding=>"unicode", :migrations_paths=>"db/migrate", :database=>"rails_devise_production"}
And the output after the block keeps the connection to the datawarehouse.
=> {:adapter=>"postgresql", :host=>"postgres-archive", :encoding=>"unicode", :migrations_paths=>"db/datawarehouse_migrate", :database=>"archive" }
How is this possible? I would expect only the code in the block to be run against the other database connection.
There's a similar question in Rails repo issues. In short, connected_to with database key is specifically for one-off connections, and you need to use the role key in your application.
I understand that from the console I can run heroku restart. What I'd like to do is to have a button in my app (admin console), where pushing that button runs a heroku restart. Does anyone know how to do that and if it's possible? So the code would look something like this:
<button id="heroku_restart">Restart</button>
$("#heroku_restart").click(function() {
$.post('/restart', {}).done(function(response) {
alert(response)
})
})
class AdminsController
# this is the action mapped to the route /restart
def restart
# code for heroku restart
end
end
So per #vpibano, as of this writing, doing it with the platform-api is a breeze. Here's the action POSTed to by a button on my website:
def restart
heroku = PlatformAPI.connect_oauth(ENV["heroku_oauth_token"])
heroku.dyno.restart_all("lastmingear")
render nothing: true
end
As per the description mentioned in the post, the one way of doing it is :
1) First locate the server.pid file
pid_file = Rails.root.join("tmp", "pids", "server.opid")
2) Now, truncate the contents of the file
File.open(pid_file, "w") {|f| f.truncate(0)}
3) Finally, run the server using Kernel module:
Kernel.exec("rails s")
Note: As rightly, mentioned by #vpibano you will need authentication to access your app.
This is not a working model but a way to achieve the requirement.
Hope it helps!!
I've written my first rake task in rails, I've set it up with the Heroku scheduler and it is getting run, however the mail isn't getting sent. My mail settings are fine as I'm using it for various other things, I would imagine it's a problem with my code in the rake task. Any help would be much appreciated.
lib/tasks/uncomplete_form.rake
desc "Remind users if they haven't completed quote form"
task uncomplete_form: :environment do
puts 'Reminding users of uncomplete quote form'
date = Date.parse('december 18 2016')
quickcontacts = Quickcontact.where(created_at: date.midnight..Time.now)
quickcontacts.each do |quickcontact|
next unless quickcontact.created_at > 1.hour.ago
if quickcontact.p_p = nil
QuickcontactMailer.uncomplete_form(#quickcontact).deliver
end
end
puts 'done.'
end
By running rake uncomplete_form I get
Reminding users of uncomplete quote form
done.
And running
heroku run rake uncomplete_form
I get
Reminding users of uncomplete quote form
Quickcontact Load (1.5ms) SELECT "quickcontacts".* FROM "quickcontacts" WHERE ("quickcontacts"."created_at" BETWEEN '2016-12-18 00:00:00.000000' AND '2016-12-20 12:09:23.683977')
done.
It doesn't seem to be picking up any quickcontacts - however if in the console I run:
date = Date.parse('december 18 2016')
followed by
quickcontacts = Quickcontact.where(created_at: date.midnight..Time.now)
It does find the expected contacts
Have you tried
QuickcontactMailer.uncomplete_form(#quickcontact).deliver_now
?
Edit: What's .p_p supposed to be? You're doing assignment in that if clause instead of what I presume should have been comparison (?)
if quickcontact.p_p = nil
Solved: Two bad errors on my part. Thanks for the help with the first #matija. The problem was with my rake task code. The first error was where I had 'if quickcontact.p_p = nil' needed to be changed to 'if quickcontact.p_p.nil?' - I was accidentally assigning nil value, rather than checking it.
The second error was that in the next line down, quickcontact should not have been an instance variable. This is the updated, functioning code:
desc "Remind users if they haven't completed quote form"
task uncomplete_form: :environment do
puts 'Reminding users of uncomplete quote form'
date = Date.parse('december 18 2016')
quickcontacts = Quickcontact.where(created_at: date.midnight..Time.now)
quickcontacts.each do |quickcontact|
next unless quickcontact.created_at > 1.hour.ago
if quickcontact.p_p.nil?
QuickcontactMailer.uncomplete_form(quickcontact).deliver
end
end
puts 'done.'
end
When I have a lot of products (3000 and 22000 variants), adding new stock location takes hours because Spree is creating stock items for every variant.
During this time variants table is locked and whole system is unusable. Is there some workaround for this or maybe it was fixed in some new version of Spree?
I am using spree 2.0.3.
I face the same problem, with >400K variants, it's impossible to add a new stock location. So, I create a script in ruby and for all variants write an insert statement to a SQL file. I must create the stock location without propagate_all_variants
# lib/create_stock_items.rb
begin
file = File.open("stock_items.sql", "w")
rescue IOError => e
puts e
end
file.write("INSERT INTO spree_stock_items (stock_location_id, variant_id, backorderable) VALUES \n")
variants = Spree::Variant.all.pluck(:id)
length = variants.count
variants.each_with_index do |variant, index|
if index+1 == length
file.write("(#{stock_location_id}, #{variant}, false); \n")
else
file.write("(#{stock_location_id}, #{variant}, false), \n")
end
end
file.close
Then run bundle exec rails runner lib/create_stock_items.rb -e production. This will create a stock_items.sql file in Rails root path, and finally load that SQL directly on BD (rails dbconsole).
I know it's a little hack, but a very fast solution for me.