SQL WHERE equivalent in rails

What is the equivalent of the WHERE SQL condition in rails?

I’m thinkin this could be something like:

<% for product in @products where category=“1” %>

but obviously the syntax is wrong.

BB wrote:

What is the equivalent of the WHERE SQL condition in rails?

I’m thinkin this could be something like:

<% for product in @products where category=“1” %>

but obviously the syntax is wrong.

Try something like this:

@products = Product.find(:all, :condition => “category = ‘1’”)

and then you can:
for product in @products

You’ll need to do that in your model or controller:

@products = product.find(:all,
:conditions => “category = 1”)

or with a variable:

@products = product.find(:all,
:conditions => [“category = ?”, category_id])

Then you can loop @products in your view.

Steve

On 4/25/06, BB [email protected] wrote:

What is the equivalent of the WHERE SQL condition in rails?

I’m thinkin this could be something like:

<% for product in @products where category=“1” %>

but obviously the syntax is wrong.

You can use:
matches = @products.select {|product| product.category == ‘1’}

Also, if you know in advance that you only want products from category
1, you can just do that in the initial find:
@products = Product.find :all, :conditions => “category = ‘1’”

I assume you’ve got something other than that in mind, though.

If you want things grouped by category, you can also do:

@products.group_by(&:category).each do |category, products|

Do stuff with the current category

Do stuff with the current set of products

end

Find out more here:
http://weblog.rubyonrails.org/articles/2006/03/01/new-in-rails-enumerable-group_by-and-array-in_groups_of

Thank you all so much, I think I understand the relationship a bit
better now and I got my app running.

On Apr 25, 2006, at 3:49 PM, BB wrote:

What is the equivalent of the WHERE SQL condition in rails?

I’m thinkin this could be something like:

<% for product in @products where category=“1” %>

but obviously the syntax is wrong.

for product in Product.find_all_by_category(1)

do something with product

end


– Tom M.

BB wrote:

Thank you all so much, I think I understand the relationship a bit
better now and I got my app running.

@category.products.each do |product|

end

class Category < ActiveRecord::Base
has_many :products
end

class Product < ActiveRecord::Base
belongs_to :category
end

(1 to many relation, you can make it many to many with :through)

Gokhan
www.sylow.net