I'm trying to write a "find_by_sql" statement that selects with a
WHERE clause comparing an attribute to an external value. My statement
generates an error on the last line:
def department
# For menu display
@departments = Department.find(:all)
@categories = Category.find_all_by_department_id(params[:id],
:order => "category_id")
# For "@department.title" and "@department.description" display
@department = Department.find_by_department_id(params[:id])
# Select products on promotion
@products = Product.find_by_sql("SELECT DISTINCT * FROM products "
I'm trying to write a "find_by_sql" statement that selects with a
WHERE clause comparing an attribute to an external value. My statement
generates an error on the last line:
Well if you just say 'an error' it's hard to guess whiich error (and
thus what problem you're encountering). I'd start byt not using a
horrible find_by_sql.
Product.find :all, :select => 'distinct products.*', :joins
=> :categories, :conditions => ['categories.department_id = ?',
params[:id]]
does the same thing as your chunk of sql.
(assuming there's a has many through (or a hatbm) from products to
categories (via product_categories)
The error message was: "wrong number of arguments (2 for 1)".
There are four tables involved: departments, products,
product_categories and categories.
A department has_many categories.
Categories and products have a many-to-many relationship, joined by a
product_categories table containing category_id paired with
product_id.
Selection has two conditions: The product record has an
on_department_promotion attribute = 'true'
and the category record has a
department_id attribute = prams[:id]
Your familiarity with Rails find statements is well beyond mine; so,
if you're so inclined, I cound use help in scripting the find
statement.
The error message was: "wrong number of arguments (2 for 1)".
Ah yes, you need to say find_by_sql([some_sql, substitution_value1,
substitution_value2])
There are four tables involved: departments, products,
product_categories and categories.
A department has_many categories.
Categories and products have a many-to-many relationship, joined by a
product_categories table containing category_id paired with
product_id.
Selection has two conditions: The product record has an
on_department_promotion attribute = 'true'
and the category record has a
department_id attribute = prams[:id]
Your familiarity with Rails find statements is well beyond mine; so,
if you're so inclined, I cound use help in scripting the find
statement.
I think what I gave below is most of the way there, just augment the
conditions a bit:
['product_on_department_promotion = ? AND categories.department_id
= ?', true, params[:id]]