Rails – Understanding how to Query An Objectin Rails 3 – Education Career Blog

if I have the following:

@projects = Permission.where("user_id >= ?", 21)

Results In:

#<Permission id: 59, project_id: 13, user_id: 21>, #<Permission id: 59, project_id: 13, user_id: 21>

I then what to use those project_id ‘s to QUERY as follows:

AuditLog.where({ :project_id => @projects }).limit(10)

But this errors?

NoMethodError: undefined method `project_id' for #<Permission id: 59, project_id: 13, user_id: 21>:ActiveRecord::Relation

Ideas? thank you


To start, let’s clean up your first query:

@permissions = Permission.where('user_id >= ?', 21)

This is less misleading about what @permissions is actually storing. Next, remember that it’s an array, and what you’re saying in the next query is “where project_id is a list of ruby permission objects”, and that doesn’t make a valid query.

You can get the info you want, though. First, use ruby’s array.map method to walk through all permissions and gather their project_id’s:

@project_ids = @permissions.map(&:project_id)

Now you can tell the database to grab all audit logs where the project_id is in the list:

@audit_logs = AuditLog.where('project_id in (?)', @project_ids)

That should give you what you need. Let me know if you have any questions.

Leave a Comment