Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails Multiple models in a single file

I would know if there is a way to have two or model model classes in a single file.

Here is a simple and very basic example:

dia_actividad.rb

class DiaActividad < ActiveRecord::Base

    self.table_name =  "dbo.DIAACTIVIDAD"
  self.primary_keys = :CASINO_ID, :DIAACTIVIDAD_ID

  attr_accessible :CASINO_ID, :DIAACTIVIDAD_ID, :DFECHAHORAINICIO, :ESTADODIA_ID

  belongs_to :dia_actividad_estado, :foreign_key => :ESTADODIA_ID

end

dia_actividad_estado.rb

class DiaActividadEstado < ActiveRecord::Base

    self.table_name =  "dbo.ESTADODIA"
  self.primary_key = :ESTADODIA_ID

  attr_accessible :ESTADODIA_ID, :CESTADODIA

end

I would like to have a file like this:

  class DiaActividad < ActiveRecord::Base

        self.table_name =  "dbo.DIAACTIVIDAD"
      self.primary_keys = :CASINO_ID, :DIAACTIVIDAD_ID

      attr_accessible :CASINO_ID, :DIAACTIVIDAD_ID, :DFECHAHORAINICIO, :ESTADODIA_ID

      belongs_to :dia_actividad_estado, :foreign_key => :ESTADODIA_ID

    end

    class DiaActividadEstado < ActiveRecord::Base

        self.table_name =  "dbo.ESTADODIA"
      self.primary_key = :ESTADODIA_ID

      attr_accessible :ESTADODIA_ID, :CESTADODIA

    end

The two classes in a single file. But i get uninitialized constant errors. When a i trying to make a reference DiaActividadEstado.

Is there any way to do that?

Thanks in advance

like image 871
Müsli Avatar asked Oct 16 '12 19:10

Müsli


2 Answers

I would strongly recommend against doing this. Having a model defined in a file which name doesn't correspond to the class name breaks Rails' autoloading mechanism (that is, whenever you find an undefined constant, require the corresponding file, and hope to find there the definition.

If you really insist in doing that, at least configure somewhere the "autoload", (read here http://www.rubyinside.com/ruby-techniques-revealed-autoload-1652.html for more info), so the missing class is searched in the correct place (autoload overrides rails "smart" requires).

like image 152
rewritten Avatar answered Oct 12 '22 19:10

rewritten


Another option would be to use a module, let's say dia.rb

module Dia
  class Actividad < ActiveRecord::Base
    ...
    belongs_to :actividad_estado, :foreign_key => :ESTADODIA_ID
  end

  class ActividadEstado < ActiveRecord::Base
    ...
  end
end

Then, you'd have to use Dia::ActividadEstado and so on.

Although the original question has a tag for rails 3, I stumbled upon it while using rails 4 and trying to achieve the same thing. So I'm not sure if that would work in rails 3.

like image 38
mlt Avatar answered Oct 12 '22 20:10

mlt