ActiveRecord Help

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)

Thanks

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

Here’s an example:

class Category
  has_many :products
end

class Product
  belongs_to :category
end

products = Product
  .joins(:category)
  .select('categories.foo, products.bar')
  .where('categories.published' => true)
  .order('products.name')

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.

2 Likes

Thanks @georgebrock I have it working now :slight_smile: