Forum: Ruby on Rails Active record question

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
bohara (Guest)
on 2005-12-01 20:28
(Received via mailing list)
Hello all,

I have two tables "products" & "productdetails" in my productdetails
table I have a foreign key field called "product_id"

If I am editing product number "3" and run the following I can get and
display the detail information.
================
def edit
	@product = Product.find(params[:id])
	@categories = Category.find_all
	@productdetails = Productdetail.find(:all, :conditions =>
["product_id = 3"])
End
================

How do make that "3" be the product id from the products table
dynamically - so it always represents the product I am currently working
on.  I've tried some different things but nothing is working.

Any help is appreciated.

Thanks,
Beau
Brad D. (Guest)
on 2005-12-01 20:40
bohara wrote:
> ================
> def edit
> 	@product = Product.find(params[:id])
> 	@categories = Category.find_all
> 	@productdetails = Productdetail.find(:all, :conditions =>
> ["product_id = 3"])
> End
> ================

Change your third line to this:
@productdetails = Productdetail.find(:first, :conditions => ["product_id
= ?", @product.id])

However, a much easier way of doing this is to define the relationship
between the two models:

# models/Product.rb
class Product < ActiveRecord::Base
   belongs_to :productdetail
end

# models/Productdetail.rb
class Productdetail < ActiveRecord::Base
   has_one :product
end

Then, all you have to do is this:
@product = Product.find(params[:id], :include => [:productdetail])

And now you have it all in one query...
This topic is locked and can not be replied to.