0
Friends, I have the following exits from the console (Rails 4.1):
Product.all
Product Load (0.2ms) SELECT "products".* FROM "products"
=> #<ActiveRecord::Relation [#<Product id: 4, cod: "160", descricao: "Sutiã", price: #<BigDecimal:103c2d810,'0.1E2',9(27)>, created_at: "2016-05-18 17:05:35", updated_at: "2016-05-18 17:05:35">]>
Size.all
Size Load (0.8ms) SELECT "sizes".* FROM "sizes"
=> #<ActiveRecord::Relation [#<Size id: 1, descricao: "P", created_at: "2016-03-09 23:23:49", updated_at: "2016-03-09 23:23:49">, #<Size id: 2, descricao: "M", created_at: "2016-03-09 23:23:56", updated_at: "2016-03-09 23:23:56">, #<Size id: 3, descricao: "G", created_at: "2016-03-09 23:24:00", updated_at: "2016-03-09 23:24:00">]>
Variation.all
Variation Load (0.2ms) SELECT "variations".* FROM "variations"
=> #<ActiveRecord::Relation [#<Variation id: 35, product_id: "4", size_id: "1", color_id: "1", quantity: 4, barcode: "160P1000001000", created_at: "2016-05-18 17:05:35", updated_at: "2016-06-01 18:45:19">, #<Variation id: 36, product_id: "4", size_id: "2", color_id: "2", quantity: 10, barcode: "160M1100001000", created_at: "2016-05-18 17:05:35", updated_at: "2016-06-01 17:15:24">]>
And when I execute this command:
Variation.joins(:product,:size,:color).select('products.cod as cod_produto,products.descricao as desc_produto,colors.descricao as desc_cor,sizes.descricao as desc_tamanho,products.price as preco,variations.quantity as quantidade,variations.barcode as cod_barras')
I get this answer:
#<ActiveRecord::Relation [#<Variation id: nil>, #<Variation id: nil>]>
What’s wrong ? If I run the direct query it returns but I need it done with active record because I need to generate a csv of it.
You could help me with an example of how to use this?
– gmadeira
Have you tried the scope? Put this example I posted on the model and call it on the console
Variation.first.variation_csv
and see if it solves the question of associations. To export in csv you would create a method in the model by passing the object with the associationsself.variation_csv
– Fladson Gomes
Yes but I need to actually take the fields of the associated tables also, not only the fields of variarions. In this your example as you would to catch the other fields?
– gmadeira
It did not work. From the following error: Variation.first.variation_csv Variation Load (0.2ms) SELECT "Variations". * FROM "Variations" ORDER BY "Variations"." id" ASC LIMIT 1 Fieldname: Undefined method `variation_csv' for #<Variation:0x00000103d8e678>. Coloquei no variation.rb, tinha um erro no seu codigo coloquei assim: scope :variation_csv, -> (product_id, size_id, color_id) { (where product_id: product_id, size_id: size_id, color_id: color_id) }
– gmadeira