Relationship between Tables


#1

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


#2

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


#3

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


#4

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


#5

Hi Simon!

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

Linus