P
P
Pavel Shcheglov2016-04-07 08:24:09
Ruby on Rails
Pavel Shcheglov, 2016-04-07 08:24:09

How to implement the association correctly?

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 can also belong to another model. Age
model records from which the parameter for the Product model is taken

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

Now everything is implemented through the belongs_to relationship:
class Product
  belongs_to :age
  ...
end

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

This solution works, but I am confused by the semantics of such a relationship, for example, how can age own a product? Or is the decision itself fundamentally wrong?
Help me please!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Y
Yuri Izotov, 2016-04-08
@hrumhrumble

Alternatively, set the Age parameter to an Active Record Enum field. More or less like this:

class Conversation < ActiveRecord::Base
  enum status: [ :active, :archived ]
end

Now you can do this with the model:
# conversation.update! status: 0
conversation.active!
conversation.active? # => true
conversation.status  # => "active"
 
# conversation.update! status: 1
conversation.archived!
conversation.archived? # => true
conversation.status    # => "archived"
 
# conversation.update! status: 1
conversation.status = "archived"
 
# conversation.update! status: nil
conversation.status = nil
conversation.status.nil? # => true
conversation.status      # => nil
 
#Автоскоупы модели для выборки по енум полю
Conversation.active
Conversation.archived

Example migration to create a field:
create_table :conversations do |t|
  t.column :status, :integer, default: 0
end

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question