please an example for use multiple data bases for my app in rails, i need create and save only one table internal and external, no all database so any idea or example explicit please??
i use mysql, the replication i dont like because is for all database and i need use only one table external.
tnks!
If I'm interpreting your question correctly, you want to know how to use a different database for one or more models in your app.
You can do this quite simply in Rails. First, you'll have to create another entry in your config/database.yml file:
production:
....
development:
...
test:
...
# Our external database
external:
adapter: mysql
host: some_host
username: some_username
password: some_password
database: some_db
Then, in your model, simply tell Rails that for this particular model, use a different connection:
class MyModel < ActiveRecord::Base
establish_connection :external
end
This will send any queries for MyModel to the external database, while all other models will use the production/development database as usual.
Please note that when you're using two different databases together, MySQL itself will not let you perform certain functions, such as joins. Otherwise, you should be fine with this approach.
well my solution is the next with help vonconrad post.
database.yml
like of vonoconrad post
MyModelconn.rb
class MyModelconnection < ActiveRecord::Base
# No corresponding table in the DB.
self.abstract_class = true
# Open a connection to the appropriate database depending
# on what RAILS_ENV is set to.
establish_connection(:connyml)
end
class User < ActiveRecord::Base
end
In users_controller.rb where i need insert into in external table with data values where i save in my Active Record of usres internal so an external swicht conection next line:
MyModelconn.connection.execute('INSERT INTO 'users' (fileld1,filed2)VALUES('#{lcfield1}','#{lcfield2}')')
and BINGO! workiT! perfect!
So dont need you again swicht back AR internal.
Related
I wrote a migration with the following (create new table named sources):
class CreateSources < ActiveRecord::Migration
def change
create_table :sources do |t|
t.string :name, null: false, default: ""
t.timestamps null: false
end
end
end
And then I modified my existing model :
class Property < ActiveRecord::Base
validates :source, allow_blank: true, inclusion: { in:
Source.all.map{ |source| source.name } }
I want to add validation to the property's source to only allow source from sources table.
And then when I run the migration, I got the following error:
ActiveRecord::StatementInvalid: Mysql2::Error: Table 'sources' doesn't exist: SELECT `sources`.* FROM `sources`
The problem is query of source table is occured when it hasn't been initialized yet.
Any tips on how I can get the migration to run?
This is run on production level. so I might can't drop all the migration and rearrange it.
Rails version 4.2.5
SQL version 5.7
Keep in mind that your Source.all.map{ |source| source.name } is going to be executed when the Property class is being loaded. The Source class might not be properly initialized at that point and there might not be a proper database connection set up. Also, you'll only access Source.all once so you'd have to restart your app if you added a new Source.
Instead, validate by hand:
class Property < ActiveRecord::Base
validate :valid_source
private
def valid_source
return if(source.blank?)
return if(Source.where(name: source).exists?)
errors.add(:source, 'Unknown source') # Or whatever you want to say
end
end
That way you're checking the sources table at the right time.
Also, I wouldn't expect the error you're seeing to occur in a migration. Perhaps you're using a model inside a migration, that is to be avoided.
As an aside, is there particular reason that you don't have belongs_to :source instead? Copying the name around like that is very error prone, using a reference (hopefully backed by a foreign key in the database) would be much safer.
Have you defined Source model? I hope so.
Here the problem looks like the loading of Property class takes priority before
migration is run and hence the issue.
All my previous projects used DatabaseCleaner, so I'm used to starting with an empty DB and creating test data within each test with FactoryGirl.
Currently, I'm working on a project that has a test database with many records. It is an sql file that all developers must import in their local test environments. The same DB is imported in the continuous integration server. I feel like having less control over the test data makes the testing process harder.
Some features allow their tests to focus on specific data, such as records that are associated to a certain user. In those cases, the preexisting data is irrelevant. Other features such as a report that displays projects of all clients do not allow me to "ignore" the preexisting data.
Is there any way to ignore the test DB contents in some tests (emulate an empty DB and create my own test data without actually deleting all rows in the test DB)? Maybe have two databases (both in the same MySQL server) and being able to switch between them (e.g., some tests use one DB, other tests use the other DB)?
Any other recommendations on how deal with to this scenario?
Thank you.
I would recommend preserving your test_database, and the 'test' environment as your 'clean' state. Then you could setup a separate database that you initially seed as your 'dirty' database. A before hook in your rails_helper file could also be setup with something like this:
RSpec.configure do |config|
config.before :each, type: :feature do |example|
if ENV['TEST_DIRTY'] || example.metadata[:test_dirty]
ActiveRecord::Base.establish_connection(
{
:adapter => 'mysql2',
:database => 'test_dirty',
:host => '127.0.0.1',
:username => 'root',
:password => 'password'
}
)
end
end
end
Your database.yml file will need configurations added for your 'dirty' database. But I think the key here is keeping your clean and dirty states separate. Cheers!
I have found that adding the following configuration to spec/rails_helper.rb will run all DB operations inside tests or before(:each) blocks as transactions, which are rolled back after each test is finished. That means we can do something like before(:each) { MyModel.delete_all }, create our own test data, run our assertions (which will only see the data we created) and after the end of the test, all preexisting data will still be in the DB because the deletion will be rolled back.
RSpec.configure do |config|
config.use_transactional_fixtures = true
end
I perodicially need to access a mysql database, my primary data store is mongo, which I access with mongoid. I want to know the best way to manage connections to mysql (with the mysql2 gem - 0.2.7) without using active record.
I current do the following ...
# In config/initializers/mysql.rb
class MySqlConnection
def self.client
#client ||= Mysql2::Client.new(host: ENV['mysql_host'],
username: ENV['mysql_username'],
password: ENV['mysql_password'],
database: ENV['mysql_database'])
end
end
and then I use connection, like so ...
rows_q = "SELECT * FROM amaizng_table WHERE great_column = '#{cool_value}' "
rows = ::MySqlConnection.client.query(rows_q)
And everything is working okay -- but I have a sneaking suspicion that I am doing something horribly wrong, and things are going to explode down the road.
Also Note, the application is hosted on heroku
Anyone know the best way to approach this?
Thanks!
Jonathan
why, just WHY would you get rid of ActiveRecord's awesomeness (or any other ORM, really) ?
class Amazing < ActiveRecord::Base
establish_connection :mysql_database
end
so simple it hurts. See this for more details.
Currently I am developing an rails project to connect the database from salesforce.com with our SQL server. Atm we use the gems 'mysql2' for the sql part and 'databasedotcom'
+ 'databasedotcom-rails' for the salesforce part.
Our problem ist, that we have the same names for the tables in both databases. So both adapter try to encapsulate them into activerecord classes and as you guess, its a big problem. Unfortunately we found no solution in the internet.
So how can I prevent the namespaceconfict?
I may not be understanding the question but I think the following would work for you.
class Account < ActiveRecord::Base
# table name is 'accounts' in mysql db
end
class SalesForceAccount < ActiveRecord::Base
establish_connection "#{Rails.env}_salesforce"
table_name = :accounts
end
With a database.yml of
development:
# your mysql credentials and adapter info
development_salesforce:
# your salesforce credentials and adapter info
To solve the problem with the conflicting namespaces, we put the module for mysql in his own namespace.
the databasedotcom gem create the models on runtime, so you just have to create models for your mysql db.
create modeles for sql
create folder named after your wished prefix in models folder (for us: Mad)
put your models in the namespacee-folder (for us: Mad)
wrap the model classes in module <namespace>
like account.rb:
module Mad
class Account < ActiveRecord::Base
attr_accessible :name, :website, :phone
end
end
now you can access the Accounts for salesforce via Account and the mysql with Mad::Account
Is there an easy 'command line/console' way of checking if a Rails app is connecting properly to MySQL?
Unfortunately, I can't get a Rails console to come up. It complains about:
/home/nexargi/www/gi/vendor/ruby/1.9.1/gems/activerecord-3.2.1/lib
/active_record/dynamic_matchers.rb:50:in `method_missing': undefined
local variable or method `abddadhocbkgid' for #<Class:0x000000036427f8> (NameError)
from /home/nexargi/www/gi/app/models/adhoc_bkg_diners_diet.rb:5:in
`<class:AdhocBkgDinersDiet>'.
The 'abddadhocbkid' is the first attribute of the first table and therefore I am thinking that it is not managing to connect to the mysql database. I need to find a way of checking if Rails can connect to the mysql database without logging into the rails console.
Here is my model code:
class AdhocBkgDinersDiet < ActiveRecord::Base
validates_presence_of :abddadhocbkgid, :abddmealdietid, :abddadultnos, :abddchildnos
validates_numericality_of :abddadultnos, :abddchildnos, greater_than_or_equal_to: 0
belongs_to :adhoc_bkg, foreign_key:abddadhocbkgid
belongs_to :meal_diet, foreign_key: :abddmealdietid
end
If you just need to check if your connection is active after it has been established, there is the ActiveRecord::Base.connected? method.
You can try connecting directly using console:
ActiveRecord::Base.establish_connection(
Rails.configuration.database_configuration[Rails.env]
)
Or if you have a model you can try finding one:
SomeModel.first