Can I create ActiveRecord objects for strings loaded with the: joins option?

I need to do something like this

class User < ActiveRecord::Base
  has_many :abuse_reports
end

class AbuseReport < ActiveRecord::Base
  belongs_to :abuser, :class_name => 'User', :foreign_key => 'abuser_id'
  belongs_to :game
end

class Game < ActiveRecord::Base
  has_many :abuse_reports
end

@top_abusers = User.page(params[:page], 
  :joins => [
    'JOIN abuse_reports ON users.id = abuse_reports.abuser_id', 
    'JOIN games ON games.id = abuse_reports.game_id'
  ], 
  :group => 'users.id',
  :select => 'users.*, count(distinct games.id) AS game_count, count(abuse_reports.id) as abuse_report_count',
  :order => 'game_count DESC, abuse_report_count DESC'
)

This works, but does not create objects for AbuseReports or Games - it just returns a bunch of strings. When I reference these objects from my view, it loads them again. Is there any way to fix this? Or some way to get this behavior without using: joins?

+5
source share
2 answers

First, you really should use: include instead of: join

User.find(:all, :include => { :abuse_reports => [ :game ] }, :order => )

or, in your case, try

User.page(params[:page], :include => { :abuse_reports => [ :game ] })

This will allow you to connect and get recordings in one shot.

( .) , :

class User < ActiveRecord::Base
  has_many :abuse_reports
  has_many :abused_games, :through => :abuse_reports
end
...

User.find(:all, :include => [ :abuse_reports, :abused_games ])

, . http://railscasts.com/episodes/23 , - (- SQL RDBMS, ). - , , :

User.find(:all, :include => [ :abuse_reports, :abused_games ], :order => 'users.abused_games_count DESC, users.abuse_reports_count DESC')

ActiveRecords SQL.

+11

, , , ActiveRecord , . , sql, AR .

, AR , SQL. , , AbuseReports. - :

some_user.abuse_reports.count

abuse_reports

+3

All Articles