Forum: Ruby on Rails Relationship between Tables

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.
Ee1a90687360cb5a8c58116d489bf93e?d=identicon&s=25 Linus Mueller (Guest)
on 2007-04-25 09:19
(Received via mailing list)
Hello,

how is it possible to specify a "has_one" attribut in an one-to-many
relationship?
This code doesn't work:

class Order < ActiveRecord::Base
  has_and_belongs_to_many :invoices
  has_one :most_recent_invoice, :order => 'date DESC'
end


Thanks and best regards,
Linus
588ab1c0a5610a7e160a3b101abb91e6?d=identicon&s=25 MichaelLatta (Guest)
on 2007-04-25 16:48
(Received via mailing list)
For this type of question you need to include the migrations for both
tables for anyone to be able to help you, and the invoice class as
well.

Do you have an order_id in the invoice table for the has one relation?
Does the invoice have a belongs_to :order association defined?

Michael

On Apr 25, 12:18 am, Linus Mueller <linus.muel...@googlemail.com>
Ee1a90687360cb5a8c58116d489bf93e?d=identicon&s=25 Linus Mueller (Guest)
on 2007-04-26 10:31
(Received via mailing list)
That is the problem. I have no order_id in the invoice table.
I have only the relationship table invoices_orders with the foreign
keys.

Class Inoice:

class Invoice < ActiveRecord::Base
  has_and_belongs_to_many :orders
end

Linus
669e19951b848d1b0dac78655e34c2a4?d=identicon&s=25 Simon Pasquier (Guest)
on 2007-04-26 21:35
(Received via mailing list)
Hi,

I would extend the habtm association:

class Order < ActiveRecord::Base
  has_and_belongs_to_many :invoices do
    def most_recent
      find :first, :order => "date DESC"
    end
  end
end

Simon
Ee1a90687360cb5a8c58116d489bf93e?d=identicon&s=25 Linus Mueller (Guest)
on 2007-05-03 14:08
(Received via mailing list)
Hi Simon!

That's a great solution! Thank you:-)

Linus
This topic is locked and can not be replied to.