Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: selecting columns from multiple tables

I am new to Rails. I have three tables a, b, c

b has 2 columns: b1 and b2

c has 2 columns: c1 and c2

a has 3 columns: a1, b1 (foreign key) and c1 (foreign key)

I want to get the distinct (b2, c2) pairs by giving a value for a1

I tried something like

a.find(:all, :joins => [:b, :c], :select => "b2, c2", :conditions => {:a => {:a1 => Time.now.midnight. ... Time.now}}, :group => "b2, c2")

The SQL that this produces works fine and I am able to see the results. But I think since I am doing a a.find, I am not able to retrieve b2, c2 from the result set.

How can I modify this so that I can get b2 and c2?

like image 330
vrp1609 Avatar asked Dec 31 '25 19:12

vrp1609


1 Answers

If you modify your :select clause to read:

foo = a.find(:all, 
       :joins => [:b, :c], 
       :select => "distinct b.b2 as b2_value, c.c2 as c2_value", 
       :conditions => {:a => {:a1 => Time.now.midnight. ... Time.now}}, 
       :group => "b.b2, c.c2") 

I believe you will retrieve an array of records. Then try the following:

b2_value = foo.first["b2_value"]

That should retrieve the value you are looking for.

Also, note that in the query I specified the table name with the columns wherever I used them -- I think it's better practice and will also avoid bad queries when you have duplicate column names (for example, created_at or id).

like image 158
Kevin Bedell Avatar answered Jan 02 '26 09:01

Kevin Bedell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!