레일

2012-09-16 5 views
0

에서 attr_accessor 및 attr_accessible에 대한 혼란이 모두 간단한 가입 신청레일

schema.rb

create_table "users", :force => true do |t| 
t.string "email" 
t.string "password_hash" 
t.string "password_salt" 
t.datetime "created_at", :null => false 
t.datetime "updated_at", :null => false 

User.rb

attr_accessible :email, :password, :password_confirmation 
attr_accessor :password 
before_save :encrypt_password 
validates_confirmation_of :password 
validates_presence_of :password, :on => :create 
validates_presence_of :email 
validates_uniqueness_of :email 
. 
. 
. 

왜 사용하는 암호가 attr_accessible 및 attr_accessor입니까? 난 attr_accessor 제거하면

은 : 암호 레일 콘솔에서 실행시, 오류가 발생했습니다 :

user = User.new 
user.password # => no method error 

을하지만 실행할 때 :

user = User.new 
user.email # => nil 

작업 user.email 의미 attr_accessor에 추가하지 않고, 왜? !!

및이가 작동 :

user = User.new 
user.password_confirmation # => nil 

을하지만 난 제거 할 때

validates_confirmation_of :password 

가 작동하지 않습니다, 왜?.

답변

8

attr_accessor 및 attr_accessible거의 동일한 철자 불구 전혀 다른 방법이다.

attr_accessor, 게터와 클래스의 인스턴스에 대한 setter 메소드를 정의하는 기본 루비 방법 :

class User 
    attr_accessor :password 
end 

u = User.new 
u.password = "secret" 
u.password # => "secret" 

attr_accessible 레일 제기하는 방법입니다 그것은 "화이트리스트에 의미 "이미 모델의 속성.

class Account < ActiveRecord::Base 
    # First, you define 2 attributes: "password" and "created_at" 
    attr_accessor :password 
    attr_accessor :created_at 

    # Now you say that you want "password" attribute 
    # to be changeable via mass-assignment, while making 
    # "created_at" to be non-changeable via mass-assignment 
    attr_accessible :password 
end 

a = Account.new 

# Perform mass-assignment (which is usually done when you update 
# your model using the attributes submitted via a web form) 
a.update_attributes(:password => "secret", :created_at => Time.now) 

a.password # => "secret" 
# "password" is changed 

a.created_at # => nil 
# "created_at" remains not changed 

을 당신은 당신의 모델의 일부 속성과 간섭 방지하기 위해 attr_accessible를 사용 attr_accessible에 열거 속성은 나중에 모델의 대량 할당 (다른 속성은 블랙리스트 및 변경되지는 않습니다 동안) 속성을 통해 변경할 수 있습니다 "외부인"(예 : 간단한 Account submission을 통해 "Account.superadmin"속성을 변경할 수 없으므로 나쁜 보안 문제 일 수 있습니다). 당신이 상관없이 "화이트리스트/블랙리스트"상태의 개별적 속성을 변경할 수

참고 : 나는이 동일한 [대량 할당]을 방지하기위한 것입니다 언급 할 가치가있다 생각

a.created_at = Time.now 

a.created_at # => 2012-09-16 10:03:14 
+0

(http://blog.mhartl.com/2008/09/21/mass-assignment-in-rails-applications/) [GitHub hack] (http://www.extremetech.com/computing/)에 허용 된 문제 120981- 해킹 - 해킹 - 수백만 건의 프로젝트 - 올해 - 수정 또는 삭제 위험에 처해 있음). –

+0

위대한, 그러나 당신은 대량 할당으로 무엇을 의미 했느냐? –

+0

"한 번에 하나씩"이동하지 않고 전체 속성 배열을 전달하는 지정. 예를 들어, 위의 예제에서 link-to의 예에서'@ user.update_attributes (params [: user])'를 사용합니다. 'attr_accessible'은 "괜찮습니다"라고 말하고, attr_accessible에 의해 언급되지 않은 것은 명시 적으로 개별적으로 업데이트 될 필요가 있다고 가정합니다. –