Forum: Ruby on Rails Active record question

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
13a75f7abb2f813fb6e7f57c2b32ccae?d=identicon&s=25 bohara (Guest)
on 2005-12-01 19: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"])

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.

3fdda7e032a5619199486d05b506ced4?d=identicon&s=25 Brad Daily (bdaily)
on 2005-12-01 19: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
= ?",])

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

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

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.