Rails - create a model instance from another model

I have an application that I create where I need one model to instantiate another model. I want every car to have 4 tires.

Automobile model

class Car < ActiveRecord::Base
  has_many :tires

  after_create :make_tires

  def make_tires
    4.times { Tire.create(car: self.id) }
  end
end

Tire model

class Tire < ActiveRecord::Base
  belongs_to :car
end

However make_tires, an error appears inside that there is no activerecord to create or a new method if I try it for Tire. When I check Tire, I don’t have such methods.

How can i fix this?

Mistake: undefined method 'create' for ActiveRecord::AttributeMethods::Serialization::Tire::Module

I tested two environments: testing and development, and they both fail with the same error.

+4
source share
2 answers

This is a name conflict. Sit and relax while I explain.

Solution with explanation:

Ruby Class ( Module). ( ) - , - ruby. :

my_class = Class.new { attr_accessor :a }
instance = my_class.new
instance.a = 3
insatnce.a   #=>
instance.class.name #=> nil

, . . ? ( ):

MyClass = my_class
my_class.name   #=> 'MyClass'

, :

class MyClass
  ...
end

. - Ruby, , , - .

. ( ), ruby ​​ Tire , .

, ActiveRecord:: Base ( ), ActiveRecord::AttributeMethods::Serialization, Tire. , ruby ​​ , .

, , , " " ( ruby ​​ Object. , Object.constants) - , :: , ::Tire.

. , , , . ActiveRecord::AttributeMethods::Serialization::Tire::Module, , .

:

:

def make_tires
  4.times { tires.create }
end

, . , , Tire::Module. :

has_many :tires, class_name: '::Tire'
+6

, , , . -, make_tires. :

def make_tires
  4.times { Tire.create(car: self) }
end

attr_accessible :car Tire. :

class Tire < ActiveRecord::Base
  belongs_to :car
  attr_accessible :car
end
0

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


All Articles