Rails Multiple Models in One File

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

Here is a simple and very simple 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 

Two classes in one file. But I get uninitialized persistent errors. When I try to make a link DiaActividadEstado.

Is there any way to do this?

Thanks in advance

+6
source share
3 answers

I would highly recommend not to do this. Having a model defined in a file whose name does not match the class name breaks the Rails autoload mechanism (i.e., whenever you find the undefined constant, you need the corresponding file and hope to find a definition there.

If you really insist on it, at least configure somewhere โ€œautoloadโ€ (read here http://www.rubyinside.com/ruby-techniques-revealed-autoload-1652.html for more information), therefore missing class search in the right place (requires smart rails auto-deletion).

+5
source

Another option is to use a module, 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 will need to use Dia::ActividadEstado etc.

Although the original question has a tag for rails 3, I came across it using rails 4 and trying to achieve the same. Therefore, I am not sure if this will work on rails 3.

+1
source

How about creating classes at runtime.

send this code snippet http://dzone.com/snippets/create-classes-runtime and let us know if it helps

0
source

Source: https://habr.com/ru/post/927876/


All Articles