Answer the question
In order to leave comments, you need to log in
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: "Детский"
class Product
belongs_to :age
...
end
create_table "products", force: :cascade do |t|
t.integer "age_id"
....
end
Answer the question
In order to leave comments, you need to log in
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
# 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
create_table :conversations do |t|
t.column :status, :integer, default: 0
end
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question