2012-06-11 22 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 

मैं वास्तव में यह करने के लिए सक्षम होना चाहते हैं:

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

मैं सिर्फ अपने दम पर update_attributes लिख सकता है, लेकिन मुझे लगता है कि यह कहीं मौजूद है। क्या यह?

उत्तर

7

नहीं है, लेकिन इस मामले के लिए आम पैटर्न है:

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 

यह from here. है उदाहरण के लिए लिंक देखें।

यदि आप स्वयं को इस दृष्टिकोण को अक्सर दोहराते हैं, तो आप इस विधि को एक अलग मॉड्यूल में निकाल सकते हैं और इसे मांग पर शामिल कर सकते हैं।

+0

हैं अभी तक नए रेल संस्करणों के लिए कोई ज्ञान? – schmijos

0

ऐसा लगता है कि वे इसे सक्रिय रिकॉर्ड से निकल गए और रेल में सक्रिय मॉडल में स्थानांतरित कर दिया 5.

http://api.rubyonrails.org/classes/ActiveModel/AttributeAssignment.html#method-i-assign_attributes

आपने मॉड्यूल शामिल करने के लिए सक्षम होना चाहिए: वहाँ

include ActiveModel::AttributeAssignment