Re: Associations - Better solution?

Älphä Blüë
2009-07-13T22:09:27Z

Ashrafuz Zaman wrote:
> Have you tried,
>
> class Audit < ActiveRecord::Base
>   belongs_to :auditor, :class_name => ''User'',
:foreign_key =>
> ''auditor_id''
>   belongs_to :tenant,  :class_name => ''User'',
:foreign_key =>
> ''tenant_id''
> end
>
> class User < ActiveRecord::Base
>   has_many :auditors
>   has_many :tenants
> end

You don''t have to specify the foreign_key in your example above.  Rails
will automatically assign a foreign key for the two models specified
using model_id and since they are auditor that means auditor_id and
tenant that means tenant_id.

You only have to specify a foreign key of you are using something
different.  As an example, if you were going to custom_id in auditor and
special_id in tenant you would have to specify the naming of the foreign
keys.

In your example:

belongs_to :auditor, :class_name => ''User''
belongs_to :tenant,  :class_name => ''User''

.. is enough.

--
Posted via http://www.ruby-forum.com/.