Pergunta

I have 2 models: Product (name, price) and Order (user_id, product_id)

Then I want to execute this query inside function in application_controller.rb

SELECT * FROM orders INNER JOIN products ON orders.product_id = products.id

It is possible to do this only with ActiveRecord and Rails associations? What should i write in models?

Foi útil?

Solução

Your models should be like:

class Product < ActiveRecord::Base
  has_many :orders
end

class Order < ActiveRecord::Base
  belongs_to :product
  belongs_to :user
end

Now you can do:

Order.joins(:product).all

But what are you trying to achieve? What is reason for this pointless join? If you just want to preload the products so there isn't any additional queries to your database, you can use includes instead of joins.

Outras dicas

I doubt that you really need join. Try eager loading:

 Order.includes(:product)

Btw maybe you should read the docs if you want to go with rails. No offense, but you can find everything about this in official Rails documentation or in huge number of tuts online. Especially, if you're beginning with Rails Michaels Hartl Learning Rails comes to mind (http://ruby.railstutorial.org/)

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top