views:

35

answers:

1

I have multiple models with created_by and modified_by columns. This is what I have for a Deal Model.

class Deal has_one :user , :foreign_key => 'created_by' has_one :user , :foreign_key => 'modified_by' end

class User belongs_to :created_by , :class_name => 'Deal' , :foreign_key => 'created_by' belongs_to :modified_by , :class_name => 'Deal' , :foreign_key => 'modified_by' end

When I create the deal, looks like it is saving correctly. But in the show view when I try to get @deal.created_by.email I get undefined method email error. Can some tell me how to get this working please?

Also since I have multiple models with these two colums, there can be many belongs_to in User model. Is there an elegant solution for this case.

Thanks DM

A: 

First thing you have to add is the specification of accessible attributes. In User you would have to add:

attr_accessible :email, :created_by, :modified_by

In Deal:

attr_accessible :created_by, :modified_by

But you should also change the direction of your relation. The foreign_key is always on the belongs_to side.

This is what worked for me:

class Deal < ActiveRecord::Base
  belongs_to  :created_by, :class_name => "User", :foreign_key => "created_by"
  belongs_to  :modified_by, :class_name => "User", :foreign_key =>"modified_by"

  attr_accessible :created_by, :modified_by, :name
end

class User < ActiveRecord::Base
  has_many :created_deals, :class_name => "Deal", :foreign_key => "created_by"
  has_many :modified_deals, :class_name => "Deal", :foreign_key => "modified_by"

  attr_accessible :created_deals, :modified_deals, :name
end

If you have more models, which look similiar you could probably use polymorphic associations: http://guides.rubyonrails.org/association_basics.html#polymorphic-associations

Patrick R.