Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails Associations with Modules

With Rails 4.1 I can't seem to get my rails associations to work when using modules.

I have Objects within the FG module:

module FG
  class Object < ActiveRecord::Base
    belongs_to :user

    has_one :email
    has_one :phone
  end
end

And Emails in the global space:

class Email < ActiveRecord::Base
  belongs_to :object, class_name: 'FG::Object'
  has_many :objects, class_name: 'FG::Object'
end

When I try

email.objects << object

I get the following error:

ActiveModel::MissingAttributeError can't write unknown attribute `object_id'

Am I missing something in the association setup?

like image 338
Chaseph Avatar asked Sep 07 '14 22:09

Chaseph


2 Answers

You could write your Email code this way:

class Email < ActiveRecord::Base
  has_many :objects, class_name: 'FG::Object', foreign_key: 'email_id'
end

This will only work if you have an email_id in your objects table. You can not use has_many and belongs_to referring to the same class. That would mean you have an object_id in the one table and an email_id in the other.

You could also write:

class Email < ActiveRecord::Base
  belongs_to :object, class_name: 'FG::Object', foreign_key: 'object_id'
end

That depends on your database construction.

like image 167
David Seeherr Avatar answered Oct 13 '22 13:10

David Seeherr


I was thinking of the relationships in a conflicting way.

In order for the associations to make sense, I needed to organize them in the following way:

module FG
  class Object < ActiveRecord::Base
    belongs_to :user

    belongs_to :email
    belongs_to :phone
  end
end

class Email < ActiveRecord::Base
  has_many :objects, class_name: 'FG::Object'
end
like image 37
Chaseph Avatar answered Oct 13 '22 15:10

Chaseph