네로개발일기

개발자 네로의 개발 일기, 자바를 좋아합니다 !

'2021/10/20'에 해당되는 글 1건


반응형

# 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

 

Add an array column in Rails

How do you declare an array column in Rails? Detail I have the following model rails generate model User address:text but I want a model which can store multiple addresses per user. The following

stackoverflow.com

http://blog.plataformatec.com.br/2014/07/rails-4-and-postgresql-arrays/

 

Rails 4 and PostgreSQL Arrays « Plataformatec Blog

In this post we show how Rails treats PostgreSQL array type, and how to use PL/pgSQL custom functions to do unique validations in PostgreSQL arrays.

blog.plataformatec.com.br

 

추가 (2021.10.23)

코드를 짜다보니 느끼는 거지만 array 칼럼보다는 1:N 연관관계로 설정하는 것이 좋아보인다 !

728x90
반응형
blog image

Written by ner.o

개발자 네로의 개발 일기, 자바를 좋아합니다 !