Rails에서 모델 속성을 어떻게 발견합니까?


142

클래스 파일에 명시 적으로 정의되어 있지 않기 때문에 모든 모델 클래스에 존재하는 속성 / 속성을 쉽게 확인하기가 어렵습니다.

모델 속성을 발견하기 위해 schema.rb 파일을 열어 놓고 필요에 따라 작성하는 코드와 그 사이를 전환합니다. 이것은 작동하지만 속성을 가져 오기 위해 스키마 파일 읽기, 메서드를 확인하기 위해 모델 클래스 파일 및 속성 및 메서드를 호출하기 위해 작성하는 새 코드 간을 전환해야하기 때문에 복잡합니다.

제 질문은, Rails 코드베이스를 처음 분석 할 때 어떻게 모델 속성을 발견합니까? schema.rb 파일을 항상 열어 놓아야합니까, 아니면 스키마 파일과 모델 파일간에 지속적으로 점프하지 않는 더 좋은 방법이 있습니까?


7
아래 답변에 감사드립니다. 모델 소스 파일에서 속성 이름을 선언하는 좋은 방법이 아니라 오히려 터미널을 열어두고 객체를 찔러서 속성을 찾습니다.
gbc

답변:


276

스키마 관련 사항

Model.column_names         
Model.columns_hash         
Model.columns 

예를 들어 AR 객체의 변수 / 속성

object.attribute_names                    
object.attribute_present?          
object.attributes

예를 들어 수퍼 클래스로부터 상속받지 않은 메소드

Model.instance_methods(false)

10
협회도 얻으려면 다음을 수행하십시오. Model.reflect_on_all_associations.map (& : name)
vasilakisfil

1
ActiveRecord 5 (및 이전 버전)에서는을 호출 할 수 있습니다 Model.attribute_names.
aceofbassgreg


15

데이터베이스의 속성 및 데이터 유형에 관심이있는 경우을 사용할 수 있습니다 Model.inspect.

irb(main):001:0> User.inspect
=> "User(id: integer, email: string, encrypted_password: string,
 reset_password_token: string, reset_password_sent_at: datetime,
 remember_created_at: datetime, sign_in_count: integer,
 current_sign_in_at: datetime, last_sign_in_at: datetime,
 current_sign_in_ip: string, last_sign_in_ip: string, created_at: datetime,
 updated_at: datetime)"

또한, 실행 한 rake db:createrake db:migrate개발 환경에 대한 파일은 db/schema.rb데이터베이스 구조에 대한 신뢰할 수있는 소스를 포함합니다 :

ActiveRecord::Schema.define(version: 20130712162401) do
  create_table "users", force: true do |t|
    t.string   "email",                  default: "", null: false
    t.string   "encrypted_password",     default: "", null: false
    t.string   "reset_password_token"
    t.datetime "reset_password_sent_at"
    t.datetime "remember_created_at"
    t.integer  "sign_in_count",          default: 0
    t.datetime "current_sign_in_at"
    t.datetime "last_sign_in_at"
    t.string   "current_sign_in_ip"
    t.string   "last_sign_in_ip"
    t.datetime "created_at"
    t.datetime "updated_at"
  end
end

10

다음 스 니펫을 사용하는 모델을 설명하기 위해

Model.columns.collect { |c| "#{c.name} (#{c.type})" }

다시 말하지만 이것은 ActiveRecord속성에서 주석을 달기에 충분하기 전에 마이그레이션을 거치거나 개발자를 호핑하지 않고 설명하기 위해 예쁜 글씨를 찾고있는 경우 입니다.


특정 모델에 대한 모든 인스턴스의 모든 속성을 인쇄하는 데 적합합니다. 감사합니다!
ConorB 2016 년

4
some_instance.attributes

출처 : 블로그


some_class.attributes.keys는 약간 더 깨끗합니다
klochner

어떤 IDE가 자동 완성을 위해 이것을 사용하는지 궁금하십니까? 레일 모델에서해야 할 일인 것 같습니다. 속성 이름을 입력하기 시작할 때 항상 실망하며 자동 완성되지 않습니다.
frankodwyer

2
@frankodwyer-RubyMine은 다른 사람이있을 것이라 확신합니다.
Matt
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.