2012-02-11 22 views
3

attribute=以外の方法でRailsのモデルに属性を設定する方法はありますか?Ruby on Rails |属性を設定する

たとえば、set_attribute(name, value)のようなものがありますか?

user = User.new 
user.set_attribute(:name, 'Jack') 
user.set_attribute(:surname, 'The Ripper') 
user.save 

# instead of 
user.name = 'Jack' 
user.surname = 'The Ripper' 

答えて

2

write_attributeメソッドがあります。それはあなたが探しているものでなければなりません。一度に多くの属性を更新したい場合は、update_attributesを使用することができます

EDIT

。我々は

# File activerecord/lib/active_record/persistence.rb, line 208 
def update_attributes(attributes, options = {}) 
    # The following transaction covers any possible database side-effects of the 
    # attributes assignment. For example, setting the IDs of a child collection. 
    with_transaction_returning_status do 
    self.assign_attributes(attributes, options) 
    save 
    end 
end 

ので、あなたが直接メソッドを呼び出すことなく、名前で属性を設定したい場合に使用することができます。また

を保存せずに属性を設定するassign_attributes(attributes, options)を使用することができます見つけることができるAR元に探して

+0

答えてくれてありがとう、lucapette。一度に複数の属性を割り当てることを可能にする同様の方法はありますか? 'write_attributes'のようなものです。 – Shamaoke

+0

[update_attributes](http://apidock.com/rails/ActiveRecord/Base/update_attributes)メソッドは即座に属性の更新(保存)に使用でき、ここでは[attributes =](http://apidock.com/rails/ ActiveRecord/Base/attributes%3D)も保存しないで元のオブジェクトを変更するだけです。 – icanhazbroccoli

+0

@Shamaoke 4pcbrは、多くの属性を一度に書きたい場合は、update_attributesを使用できます。 – lucapette

3

の代わりにuser.send(:name=, 'Jack')

関連する問題