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
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
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
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 Mueller wrote:
Hi Simon!
That's a great solution! Thank you:-)
Linus