Jump to content

The ultimate community for Ruby on Rails developers.


Photo

ActiveRecord

rails ruby activerecord mysq joins

  • Please log in to reply
3 replies to this topic

#1 conal4284

conal4284

    Passenger

  • Members
  • 7 posts

Posted 06 September 2013 - 10:55 AM

I want to join two tables and select columns from both tables, equivalent sql is as follows :

Using Rails 2.3.15

 

select p.id, p.title, p.img_url, p.url, pp.selling_price from products p inner join product_pricings pp on p.id = pp.product_id where p.is_best_selling_showcase = 1

 

What should be the equivalend ActiveRecord code for making this kind of joins. Any suggestions would help me lot.

Thanks in advance.



#2 Rowel

Rowel

    Controller

  • Members
  • 109 posts

Posted 06 September 2013 - 01:33 PM

I think the Rails way of doing this is 

product.product_pricings.where(best_selling_showcase: true) 

But I don't think that necessarily produces an actual SQL JOIN behind the scenes, though I think that's the behavior that you want. 

 

The advantage of Rails ActiveRecord associations is it insulates you from the underlying SQL, if you've setup the associations (has_many, belongs_to, etc.) correctly. No SQL knowledge needed. 

 

The disadvantage of Rails ActiveRecord associations is it insulates you from the underlying SQL, less control on the SQL command generated by Rails. 



#3 Vito Botta

Vito Botta

    Signalman

  • Members
  • 12 posts
  • LocationEspoo, Finland

Posted 15 September 2013 - 08:32 PM

Is the association between product and product pricing just a one to many?



#4 katafrakt

katafrakt

    Signalman

  • Members
  • 16 posts
  • LocationKrak√≥w, PL

Posted 18 September 2013 - 02:10 PM

Normally you would do something like

Product.joins(:product_pricings).where(:best_selling_showcase => 1)

but it won't work in 2.3.15 (actually in any version below 3.0.0).

 

The 2.3.x version of this would be probably

Product.find(:includes => :product_pricings, :conditions => {:best_selling_showcase => 1})






Also tagged with one or more of these keywords: rails, ruby, activerecord, mysq, joins

0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users