[Ruby on Rails] ORM rails generate model array column: 모델에 배열 데이터 타입 저장
2021. 10. 20. 23:47
반응형
# rails how to generate model array column
model을 만들 때 rails g model 명령어를 사용한다.
$ rails g model user Article title:string body:text
class CreateArticles < ActiveRecord::Migration[6.0]
def change
create_table :articles do |t|
t.string :title
t.text :body
t.timestamps
end
end
end
위 명령어를 사용하면 위와 같은 Migration 파일이 생성된다.
title은 string 타입으로, body는 text 타입으로 테이블이 생성된다.
아래 명령어를 통해 들어가보면
$ rails g model --help
Available field types:
Just after the field name you can specify a type like text or boolean.
It will generate the column with the associated SQL type.
For instance:
`rails generate model post title:string body:text`
will generate a title column with a varchar type and a body column with a text
type. If no type is specified the string type will be used by default.
You can use the following types:
integer
primary_key
decimal
float
boolean
binary
string
text
date
time
datetime
You can also consider `references` as a kind of type.
For instance, if you run:
`rails generate model photo title:string album:references`
It will generate an `album_id` column. You should generate these kinds of fields when
you will use a `belongs_to` association, for instance.
`references` also supports
polymorphism, you can enable polymorphism like this:
`rails generate model product supplier:references{polymorphic}`
For integer, string, text and binary fields, an integer in curly braces will
be set as the limit:
`rails generate model user pseudo:string{30}`
For decimal, two integers separated by a comma in curly braces will be used
for precision and scale:
`rails generate model product 'price:decimal{10,2}'`
You can add a `:uniq` or `:index` suffix for unique or standard indexes
respectively:
`rails generate model user pseudo:string:uniq`
`rails generate model user pseudo:string:index`
You can combine any single curly brace option with the index options:
`rails generate model user username:string{30}:uniq`
`rails generate model product supplier:references{polymorphic}:index`
If you require a `password_digest` string column for use with
has_secure_password, you can specify `password:digest`:
`rails generate model user password:digest`
If you require a `token` string column for use with
has_secure_token, you can specify `auth_token:token`:
`rails generate model user auth_token:token`
그런데 배열 타입의 칼럼을 생성할 수 있지 않을까 하는 의문이 들었다 !
1. migration 파일을 만들어준다.
$ rails g migration Article add_subjects_to_article subjects:text
명령어 설명
- g: generate => g migration 하면 migration 파일을 만들어준다. 예) g controller... , g model ... 등등
- Article: 대신 Table 명
- add_subjects_to_article: 설정하고 싶은 migration 파일 이름
- subjects:text: subjects을 text 타입으로
2. DB가 PostgreSQL인 경우 migration 파일에 다음과 같이 추가해준다.
class AddSubjectsToArticle < ActiveRecord::Migration
def change
add_column :articles, :subjects, :text, array: true, default: []
end
end
여기서 중요한 것은 array: true, default: [] 이다. 이 부분을 직접 작성해준다.
2-1. DB가 SQLite3인 경우 app> models> article.rb 에서
클래스 안에 serialize :subjects, Array 라고 작성한다.
3. migrate를 한다.
$ rails db:migrate
출처
https://stackoverflow.com/questions/32409820/add-an-array-column-in-rails
http://blog.plataformatec.com.br/2014/07/rails-4-and-postgresql-arrays/
추가 (2021.10.23)
코드를 짜다보니 느끼는 거지만 array 칼럼보다는 1:N 연관관계로 설정하는 것이 좋아보인다 !
728x90
반응형
'web > Ruby on Rails' 카테고리의 다른 글
[Ruby on Rails] 페이지 (paginate) Gem: kaminari (0) | 2022.06.27 |
---|---|
[Ruby On Rails] Gem (0) | 2022.05.09 |
[Ruby on Rails] Rails console을 이용해서 데이터베이스 테이블 확인하는 방법/How to list database tables using the "rails console"? (1) | 2021.10.22 |
[Ruby on Rails] Ruby Time.now vs Time.current (0) | 2021.10.21 |
[Ruby on Rails] bundle install mysql2 error on Mac m1 (zstd ssl library not found) (1) | 2021.09.28 |
Written by ner.o
개발자 네로의 개발 일기,
자바를 좋아합니다 !
댓글 개