Forum: Ruby on Rails Problems with belongs_to table joins

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.
RobL (Guest)
on 2006-05-19 20:30
I am looking for a little assistance with a problem I have with a simple
table join using Rails. I am a relative newbie to both Ruby and Rails so
any help would be greatly appreciated . I have two tables products and

create table products (
        id      int     not null auto_increment,
        title   varchar(100)    not null,
        product_format_id       integer references product_formats(id),
        description     text    not null,
        image_url       varchar(200)    not null,
        products_quantity       int(11) not null,
        products_status         enum('0','1') not null,
        available_from          date,
        cost_price      decimal(10,2)   not null,
        retail_price    decimal(10,2)   not null,
        primary key(id)

class Product < ActiveRecord::Base

  validates_presence_of :title
  validates_numericality_of :retail_price, :cost_price

  has_and_belongs_to_many :artists
  has_and_belongs_to_many :labels
  has_and_belongs_to_many :genres

  belongs_to :product_formats


create table product_formats (
        id      int     not null auto_increment,
        format  varchar(30),
        primary key(id)

class ProductFormat < ActiveRecord::Base

I have successfully created many to many table joins and they are
working fine. But alas I can quite stumped on how to get a one to many
join working ok.

I would just like to list out the products and (where the type is
specified their type)

  def testlist
    @products = Product.find(:all)

As far as I know the above will select all the products from the table
and the belongs_to method will automagically create the method


so in theory I should be able to list product information like so

<%=product.title%> <%=product.product_format_id%>

However, I keep getting the following error, which is presumably
indicating that the join hasn't occured. Indeed looking in the
development.log I can't see any join or select from the table

undefined method `product_format' for #<Product:0xb789c580>

Can anyone steer me in the right direction?
Michael T. (Guest)
on 2006-05-19 20:48
(Received via mailing list)
class ProductFormat < ActiveRecord::Base
  has_many :products
RobL (Guest)
on 2006-05-19 22:24
Michael T. wrote:
> class ProductFormat < ActiveRecord::Base
>   has_many :products
> end

Thanks, but to be honest I had tried that as well, but as far as I can
tell from other working  applications this isn't always necessary.
Either way, I have added this my product_format.rb model and its still
giving the same error :S
This topic is locked and can not be replied to.