방법은 두 가지가 있다.

1. rails generate model - 명령어로 모델과 함께 생성 - 모델을 생성한다.
ex. rails generate model device_wifi_info mac_address:string{16} dhcp:boolean dm_port:integer

다음과 같이 index를 추가하면 DB에 index가 붙게 되고 migration 파일에 다음과 같이 추가된다.
rails generate model people patient_id:string:index

migration 파일에선:
       add_index :people, :patient_id
DB에선:
     INDEX `index_people_on_patient_id` (`patient_id`) USING BTREE

2. rails generate migration - 명령어를 사용해서 마이그레이션 파일만 생성 - 기존 모델을 update한다.
AddXxxxxTo<테이블이름> - 필드 추가
ex 
rails generate migration AddDeletedAtToDevice deleted_at:datetime:index
deleted_at이란 datetime 필드에 index도 추가하게 한다.
결과 파일은 다음과 같다.
----------------------------
class AddDeletedAtToDevice < ActiveRecord::Migration
  def change
    add_column :devices, :deleted_at, :datetime
    add_index :devices, :deleted_at
  end
end
------------------------------


RemoveXxxxxFrom<테이블 이름> - 필드 제거
rails generate migration RemoveColumnPolicyPermFromPermissions policy_menu_perm:integer

3. scaffold로 생성하기  : Model  + View + Controller
ex. rails generate scaffold Post name:string title:string content:text



by 무위자연 2016. 3. 21. 10:08

모델에서 데이터를 추출할 때 쿼리에서의 not like를 구현하고 싶을때.


@perms = PaperTrail::Version.where(item_type: "Device").where.not(object_changes: ["%last_qc%"]).order('created_at DESC').limit(50)

- 이렇게 했을 경우에 쿼리는 다음과 같이 나오게 된다.

select  * from versions where item_type = "device" and ( object_changes != '%last_qc%') order by created_at DESC limit 50

이 것의 의미는 "%last_qc%"를 비교하는 쿼리가 된다. 즉 "" 안에 있는 %가 like가 아닌 % 문자열로 인식하게 된다.


PaperTrail::Version.where(item_type: "Device").where.not("object_changes LIKE?","%last_qc%").order('created_at DESC').limit(50)

> 컬럼명 안에 "LIKE?"를 넣어서 not이 아닌 not like로 인식하는 쿼리가 되게 한다.


select  * from versions where item_type = "device" and ( not(object_changes LIKE '%last_qc%')) order by created_at DESC limit 50



by 무위자연 2016. 2. 18. 17:24
| 1 |