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.
Linus M. (Guest)
on 2007-04-25 11: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
MichaelLatta (Guest)
on 2007-04-25 18: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 M. <removed_email_address@domain.invalid>
Linus M. (Guest)
on 2007-04-26 12: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
Simon P. (Guest)
on 2007-04-26 23: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
Linus M. (Guest)
on 2007-05-03 16: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.