I have a Rails app A with a postgres database. I also have another Rails app B with a postgres database. Now I want to reuse some of the data of app B in app A. What is the best way to import that data? I assume a rake task can be used for this, but how would you do this?
Do you need to add the connection details of the database of app B in the database.yml of app A? And how do I actually get the data?
You can do a manual connection via activerecord
require 'active_record'
ActiveRecord::Base.establish_connection(
:adapter => "mysql",
:host => "localhost",
:username => "root",
:password => "abcd",
:database => "funonrails")
or do something like this
dbconfig = YAML::load(File.open('database.yml'))
ActiveRecord::Base.establish_connection( dbconfig[:students_development] )
Depending on what you actually mean by import, you could use dblink to query the other DB directly:
http://postgresql.org/docs/current/static/dblink.html
When PostgreSQL 9.3 gets released, be sure to also look into the new foreign data wrapper:
http://postgresql.org/docs/9.3/static/postgres-fdw.html
I want to display the movies associated to a given author. On the author's page, I want users to be able to paginate, sort, and filter by keyword.
Everything works fine on my local machine. But, in production, the list of movies on the author's page is empty, and I can't figure out why. In production, in the console, I tested the following expressions, but no luck (always returns 0, while it returns values > 0 in dev):
ruby-1.9.2-p290 :042 > Movie.search(:with => {:author_ids => [6]}).count
=> 0
ruby-1.9.2-p290 :043 > Movie.search(:with => {:author_ids => 6}).count
=> 0
The weird thing is that I'm using a very similar code to display the movies associated to a topic on a topic's page, and it works great in development AND in production. For instance:
ruby-1.9.2-p290 :051 > Movie.search(:with => {:topic_ids => 2}, :per_page => 1000).count
=> 295
Here is how I define my Movie class:
class Movie < ActiveRecord::Base
belongs_to :author
has_many :topics
...
define_index('movie') do
...
has author(:id), :as => :author_ids,
:facet => true
has topics(:id), :as => :topic_ids,
:facet => true
...
end
...
end
And here is what my Author show controller looks like:
def show
#author = Author.find(params[:id])
keywords = params[:what] || ""
with_params[:author_ids] = [#author.id]
#movies = Movie.search(
keywords,
:with => with_params
)
end
This leads me to believe there is something wrong with the Sphinx index in production, but I'm not sure how to investigate further to find the root of the problem...
UPDATE: Following Pat's suggestion, I updated Sphinx and everything was solved (I upgraded from 0.9.8 to 0.9.10)! I was confused because Sphinx is NOT a Gem (even though a Sphinx gem exists)... So I had to go through the regular download, make, make install process.
I'll start with the obvious, but maybe this has already been tried - is the author_ids attribute something relatively new? Have you rebuilt (indexed and restarted) Sphinx since adding that attribute? rake ts:rebuild is the easy way to do that.
Update: It turns out updating Sphinx was the fix here - Alex can confirm which version, but I'm guessing 0.9.9 or better should do the trick.
What I am trying to achieve is something similar to Github's way for routes. E.g. I have a project with the name 'question' results in the URL /hjuskewycz/question. So my goal is to have routes where the first segment is the username and the second the project's name.
I tried a couple of different approaches, this is the one I am stuck with right now:
scope ":username" do
resources :projects, :path => "" do
resources :pictures
end
end
Using
project_path :username => project.owner.username, :id => project.to_param
works as expected. However, it's tedious to always specify the username although it's always the owner's username. I would very much prefer
project_path(:id => project.to_param)
I know about default_url_options and url_for and I digged in the code. However, polymorphic_url doesn't use default_url_options.
I tried in routes.rb:
resources :projects, :path => "", :defaults => {:username => Proc.new { "just_testing" }}
since you can use a proc for constrains, but haven't got it working either.
I tried in project.rb
def to_param
"#{owner.username"/#{project.title}"
end
I spent already too much time on this problem and my current approach uses a convenience method to add the :username parameter. Nevertheless, I think using this method all over the place just to add an entry stinks (bad code smell). I wonder if there is a more elegant solution to this problem.
I think you should not make things complicated here, just use something like this:
In Routes.rb
match ':username/:projectname/' => 'projects#show_project' , :as => :show_project
and in project_controller, just define this
def show_project
#user =User.find_by_username(params[:username])
#project =Project.find_by_slug(params[:projectname])
end
Simpler is better, it saves time and easy to understand for others
You want to do something like this in your controller:
before_filter :set_username
def set_username
Rails.application.routes.default_url_options[:username] = #user.name
end
I would like to print into log or console the executing sql. Where can I make some settings? In hibernate it is in a config file possibility: I think here should be something like that too.
I have a code part similar to this:
myresult = MyActiveRecordClass.find(:all, :select => "mytable1.*, mytable2.field1", :joins => :mytable2, :conditions => "somefield= #{somefield}", :order => "another_field desc", :offset => offset, :limit => limit)
This is a simpler case to translate by hand, but I would like to have all the native sql in a console or in file. It could be usefully at searching
Rails already displays the SQL in the development log and console (at debug log level - so ensure that the logger is able to display debug log messages).
To also display where in the source code a SQL was called from:
Rails 2: query_trace plugin
Rails 3: Tracing Rails 3 SQL queries (based on query_trace, but works for Rails 3 because query_trace does not currently work on Rails 3)
I would like to see the SQL statement that a given ActiveRecord Query will generate. I recognize I can get this information from the log after the query has been issued, but I'm wondering if there is a method that can be called on and ActiveRecord Query.
For example:
SampleModel.find(:all, :select => "DISTINCT(*)", :conditions => ["`date` > #{self.date}"], :limit => 1, :order => '`date`', :group => "`date`")
I would like to open the irb console and tack a method on the end that would show the SQL that this query will generate, but not necessarily execute the query.
Similar to penger's, but works anytime in the console even after classes have been loaded and the logger has been cached:
For Rails 2:
ActiveRecord::Base.connection.instance_variable_set :#logger, Logger.new(STDOUT)
For Rails 3.0.x:
ActiveRecord::Base.logger = Logger.new(STDOUT)
For Rails >= 3.1.0 this is already done by default in consoles. In case it's too noisy and you want to turn it off you can do:
ActiveRecord::Base.logger = nil
Stick a puts query_object.class somewhere to see what type of object your working with, then lookup the docs.
For example, in Rails 3.0, scopes use ActiveRecord::Relation which has a #to_sql method. For example:
class Contact < ActiveRecord::Base
scope :frequently_contacted, where('messages_count > 10000')
end
Then, somewhere you can do:
puts Contact.frequently_contacted.to_sql
just use to_sql method and it'll output the sql query that will be run. it works on an active record relation.
irb(main):033:0> User.limit(10).where(:username => 'banana').to_sql
=> "SELECT "users".* FROM "users" WHERE "users"."username" = 'banana'
LIMIT 10"
when doing find, it won't work, so you'll need to add that id manually to the query or run it using where.
irb(main):037:0* User.where(id: 1).to_sql
=> "SELECT "users".* FROM "users" WHERE "users"."id" = 1"
This may be an old question but I use:
SampleModel.find(:all,
:select => "DISTINCT(*)",
:conditions => ["`date` > #{self.date}"],
:limit=> 1,
:order => '`date`',
:group => "`date`"
).explain
The explain method will give quite a detailed SQL statement on what its going to do
This is what I usually do to get SQL generated in console
-> script/console
Loading development environment (Rails 2.1.2)
>> ActiveRecord::Base.logger = Logger.new STDOUT
>> Event.first
You have to do this when you first start the console, if you do this after you have typed some code, it doesn't seem to work
Can't really take credit for this, found it long time ago from someone's blog and can't remember whose it is.
When last I tried to do this there was no official way to do it. I resorted to using the function that find and its friends use to generate their queries directly. It is private API so there is a huge risk that Rails 3 will totally break it, but for debugging, it is an ok solution.
The method is construct_finder_sql(options) (lib/active_record/base.rb:1681) you will have to use send because it is private.
Edit: construct_finder_sql was removed in Rails 5.1.0.beta1.
Create a .irbrc file in your home directory and paste this in:
if ENV.include?('RAILS_ENV') && !Object.const_defined?('RAILS_DEFAULT_LOGGER')
require 'logger'
RAILS_DEFAULT_LOGGER = Logger.new(STDOUT)
end
That will output SQL statements into your irb session as you go.
EDIT: Sorry that will execute the query still, but it's closest I know of.
EDIT: Now with arel, you can build up scopes/methods as long as the object returns ActiveRecord::Relation and call .to_sql on it and it will out put the sql that is going to be executed.
My typical way to see what sql it uses is to introduce a "bug" in the sql, then you'll get an error messages spit out to the normal logger (and web screen) that has the sql in question. No need to find where stdout is going...
Try the show_sql plugin. The plugin enables you to print the SQL without running it
SampleModel.sql(:select => "DISTINCT(*)", :conditions => ["`date` > #{self.date}"], :limit => 1, :order => '`date`', :group => "`date`")
You could change the connection's log method to raise an exception, preventing the query from being run.
It's a total hack, but it seems to work for me (Rails 2.2.2, MySQL):
module ActiveRecord
module ConnectionAdapters
class AbstractAdapter
def log_with_raise(sql, name, &block)
puts sql
raise 'aborting select' if caller.any? { |l| l =~ /`select'/ }
log_without_raise(sql, name, &block)
end
alias_method_chain :log, :raise
end
end
end
You can simply use to_sql() function with the active record
Form.where(status:"Active").to_sql
In Rails 3 you can add this line to the config/environments/development.rb
config.active_record.logger = Logger.new(STDOUT)
It will however execute the query. But half got answered :