8

개발자! 나는 내가 가진 예를 들어 다음 상황가상 속성 및 대량 할당

을 이해할 수없는 모델

class Pg::City < ActiveRecord::Base 
    belongs_to :country 
    #virtual accessors 
    attr_accessor :population 
    #attr_accessible :city, :isdisabled, :country_id 

end 

나는 다음과 같은 코드를 사용할 수 있습니다

c = Pg::City.new({:population=>1000}) 
puts c.population 
1000 

을하지만 경고를 던져 위 attr_accessible 코드의 주석을 해제하는 경우

WARNING: Can't mass-assign protected attributes: population 

모델 속성과 함께 대량 assigmment에 가상 속성을 사용할 수 있습니까? 감사합니다.

+0

당신이'추가하는 시도 했습니까? –

+0

방금 ​​시도한 c = Pg :: City.new ({: population => 1000, : city => "somename"}) .... 경고 – Fivell

+1

주석 처리 된'attr_accessible' 행을 사용 해보았습니까? –

답변

21

attr_accessor을 사용하여 변수를 추가해도 자동으로이 변수가 attr_accessible에 추가되지 않습니다. 당신이 attr_accessible을 사용하려는 경우, 당신은 목록에 :population을 추가해야합니다 population` 당신이`attr_accessible`에 전달하는 인수에 :

attr_accessor :population 
attr_accessible :city, :isdisabled, :country_id, :population