Hello!

There is a Product model that has only one parameter, for example, age, which is taken from the record of the corresponding Age model, but this parameter may also belong to another model.

Entries of the Age model from which the parameter is taken for the Product model look like this:

Age.all id: 1, name: "Взрослый" id: 2, name: "Юниор" id: 3, name: "Детский" 

Now everything works through the belongs_to link:

 class Product belongs_to :age ... end 

Table Schema Products

 create_table "products", force: :cascade do |t| t.integer "age_id" .... end 

So generally the right thing to do? It confuses me that now Product belongs to a parameter, although it probably should be the other way around.

For example:

 class Product has_one :age ... end 

and something on the back of the link.

    3 answers 3

    No, no, it should be.

    Do not attach belongs_to more value than it has: this association means that this model has a foreign key ( <что-то>_id ), a link to some line in the database.

    has_ a second that the link would be located on the reverse side, because the has_ associations has_ this. Submitted? Mad? Hehe.

    This column can be made in any table. You can even have several in one (if it makes sense; then you have to specify the foreign keys yourself in at least one case, and you will have to name the associations differently).

    How then to get all the objects "belonging" to the model? Well ... First make sure you need it at all. Heterogeneous lists are rarely needed. As a rule, you want models of only one type, or, at most, of the heirs (STI) of one model - it is important that from a single table. Since relational databases represent data in the form of tables, to pack objects of different types into one set means to get kilograms of NULL s in each line, which is irrational.

    Just make separate has_many for each such connection, if you need a connection in this direction at all.

      Age:

       class Age < ActiveRecord::Base has_many :products end 

      Product:

       class Product < ActiveRecord::Base # Таблица с продуктами содержит внешний ключ belongs_to :age end 

      How does it work:

       Age.first.products # Продукты с одним возрастом Product.first.age.name # Имя возраста, указанного у продукта 
      • This is how it is implemented, just the semantics of relations in this case implies that it is not the parameter that belongs to the product, but the other way around, which is a bit contradictory. The question is how exactly such connections are designed, maybe there is a more correct option without using foreign keys in the product table for example. - Pavel Scheglov

      It seems to be all right, if you need to get age on a specific product: @product = Product.first @ product.age - you will get the age of a specific product object.