Re: How to get combined result from two tables by foreign key in ruby - datamapper

25 views
Skip to first unread message

manu

unread,
Dec 1, 2012, 7:32:06 PM12/1/12
to datam...@googlegroups.com
Assuming you're rendering this in e.g. an erb view:

@my_users = User.all(:age.gt => 25) 
erb :view

... and in the view, when displaying your table and the org column... (pseudo code)

@my_users.each |user| do
<%= Organization.get(user.organization_id).name%>

i'm not 100% this is correct, and I'm sure there's a more elegant way than calling the model directly in the view. But that's what I ted to do when elegance eludes me.





On Saturday, December 1, 2012 2:26:43 AM UTC+1, Jai Kumar wrote:
I have two tables

users
-------
id
name
organization_id


organizations
----------
id
org_name
org_unique_num
abc
xyz

organization_id in users table is foreign key to organizations table's id

class Organization
  include DataMapper::Resource
  property :id, Serial
  property :org_name, String
  property :org_unique_num, Integer
  property :abc String
  property :xyz String
  has n,    :users 
end

class User
  include DataMapper::Resource
  property :id, Serial
  property :name, String
  property :organization_id, Integer
  property :age, Integer
  belongs_to :organization 
end

I want to grab the user's record with joining Organization table where user's age > 25. So the result should look like

user_id    name    organization_id    org_name   org_unique_num    age
12           John       356                       ATT           76763               38
35           Lisa        981                       IBM            2376                28

So how can I achieve this? Please note I dont want column abc and xyz in the result.

User.all(:age.gt => 25) 

This will just give me users with age >25, but I want to grab user's org info as well. Is it possible to do it one statement? or will have to do it in multiple steps. Like collecting all user_id then pass to Organization model to with org_id in().. that would be ugly.

Any help will be appreciated.
Reply all
Reply to author
Forward
0 new messages