← Back to Upcase

ActiveRecord Help

(Scott Hollinshead) #1

How would I do this the Rails way using ActiveRecord?

title = params[:title].gsub("_", " ").gsub(":", "&")
sql = "select a.prnum, b.groupcode from customer_products a join matrixprods b on a.prnum = b.prnum"
sql += " where b.groupcode = '#{params[:id]}' and a.display_group_name = '#{title}'"
sql += " order by b.sortorder, b.prnum"
@matrix_products = Matrixprod.find_by_sql(sql)


(George Brocklehurst) #2

You can probably use the joins method and the select method.

Here’s an example:

class Category
  has_many :products

class Product
  belongs_to :category

products = Product
  .select('categories.foo, products.bar')
  .where('categories.published' => true)

product = products.first

product.foo # => the foo field from the product's category
product.bar # => the bar field from the product
product.id # => NoMethodError, we didn't load the product's id field

The Active Record query interface guide has more information about all of these methods.

(Scott Hollinshead) #3

Thanks @georgebrock I have it working now :slight_smile: