SQL WHERE equivalent in rails


#1

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.


#2

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


#3

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


#4

On 4/25/06, BB removed_email_address@domain.invalid 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


#5

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


#6

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.


#7

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