Skip to content

Instantly share code, notes, and snippets.

@nkwhr
Created May 29, 2014 01:20
Show Gist options
  • Save nkwhr/6b56b07b5bf2ca00ff37 to your computer and use it in GitHub Desktop.
Save nkwhr/6b56b07b5bf2ca00ff37 to your computer and use it in GitHub Desktop.
joinした結果を全て取得するやつ
class Model < ActiveRecord::Base
scope :retrieve_all, ->(*tables) {
select_stmt = [%{`#{self.table_name}`.*}]
select_stmt << tables.map {|t|
ar = ActiveRecord::Base.const_get(t.to_s.classify.singularize)
table_name = ar.table_name
table_name_single = table_name.singularize
ar.attribute_names.map {|col|
col == 'id' ? nil : %{`#{table_name}`.`#{col}` as `#{table_name_single}_#{col}`}
}
}
joins(*tables).select(select_stmt.flatten.compact.join(","))
}
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment