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
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With