# Create ActiveRecord instances from a custom query?

**URL:** <https://www.ruby-forum.com/t/create-activerecord-instances-from-a-custom-query/119160>\
**Category:** Rails\
**Created:** [November 4, 2007, 1:49am UTC](https://www.ruby-forum.com/t/create-activerecord-instances-from-a-custom-query/119160 "2007-11-04T01:49:31Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![josh](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/45deac/32.png) [@josh](https://www.ruby-forum.com/u/josh)\
**Post date:** [November 4, 2007, 1:49am UTC](https://www.ruby-forum.com/t/create-activerecord-instances-from-a-custom-query/119160/1 "2007-11-04T01:49:31Z")

</div>

Hi all

I’m having the following method:

def setup\_owned\_system\_rights  
@owned\_system\_rights = {}  
system\_groups.each do |system\_group|  
system\_group.system\_rights.each do |system\_right|  
@owned\_system\_rights[system\_right.model\_class.to\_sym] = {}  
unless @owned\_system\_rights[system\_right.model\_class.to\_sym]  
@owned\_system\_rights[system\_right.model\_class.to\_sym][system\_right.name.to\_sym]  
= true  
end  
end  
end

To reduce the queries to the database I’ve written the following SQL  
statement which returns the same system\_rights that the above iterations  
do:

select \* from system\_rights  
inner join system\_groups\_have\_system\_rights on system\_rights.id =  
system\_groups\_have\_system\_rights.system\_right\_id  
inner join members\_belong\_to\_system\_groups on  
members\_belong\_to\_system\_groups.system\_group\_id =  
system\_groups\_have\_system\_rights.system\_group\_id  
where members\_belong\_to\_system\_groups.member\_id = \<\<logged in member’s  
ID\>\>

How can I create now ActiveRecord objects (to be more specific:  
SystemRight model objects) out of the rows I get?

Thanks for help 🙂

---

<div class="post-metadata">

**Author:** ![josh](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/45deac/32.png) [@josh](https://www.ruby-forum.com/u/josh)\
**Post date:** [November 4, 2007, 11:54am UTC](https://www.ruby-forum.com/t/create-activerecord-instances-from-a-custom-query/119160/2 "2007-11-04T11:54:17Z")

</div>

On 4 Nov 2007, at 00:49, Joshua M. wrote:

> How can I create now ActiveRecord objects (to be more specific:  
> SystemRight model objects) out of the rows I get?

SystemRight.find\_by\_sql ‘some chunk of sql’

Fred
