2012-06-11 5 views
7

나는이처럼 내 레일 응용 프로그램에 ActiveModel 클래스를 설정 한 :ActiveModel에 "update_attributes"메소드가 포함 된 모듈이 있습니까?

class MyThingy 
    extend ActiveModel::Naming 
    extend ActiveModel::Translation 
    include ActiveModel::Validations 
    include ActiveModel::Conversion 

    attr_accessor :username, :favorite_color, :stuff 

    def initialize(params) 
    #Set up stuff 
    end 

end 
난 정말이 할 수 있기를 원하는

: 난 그냥 내 자신에 update_attributes를 작성할 수

thingy = MyThingy.new(params) 
thingy.update_attributes(:favorite_color => :red, :stuff => 'other stuff') 

을, 하지만 어딘가에 존재한다는 느낌이 들었습니다. 그거야?

답변

7

아니,하지만이 경우에 대한 일반적인 패턴이 : 그것은 from here.

class Customer 
    include ActiveModel::MassAssignmentSecurity 

    attr_accessor :name, :credit_rating 

    attr_accessible :name 
    attr_accessible :name, :credit_rating, :as => :admin 

    def assign_attributes(values, options = {}) 
    sanitize_for_mass_assignment(values, options[:as]).each do |k, v| 
     send("#{k}=", v) 
    end 
    end 
end 

이 예에 대한 링크를 참조하십시오.

이 방법을 자주 반복하는 경우이 방법을 별도 모듈로 추출하여 필요에 따라 포함시킬 수 있습니다.

+0

이 거기에가 새로운 레일 버전에 대한 어떤 계시인가? – schmijos

관련 문제