2013-04-23 110 views
1

我正在爲iPhone應用程序的後端構建Rails服務器。 Rails將JSON發送到前端,我發現自己正在做這樣的事情。爲模型實例對象創建屬性的最佳方法

@user = User.find(1) 

@user["status"] = "Some cool status" 

render :json => @user.to_json 

在我的RSpec的測試中,我得到

DEPRECATION WARNING: You're trying to create an attribute `status'. Writing arbitrary attributes on a model is deprecated. Please just use `attr_writer` etc. 

我發現很難找到一個合適的替代時,它只是簡單寫一個鍵值,將被髮送到iPhone的對象。

我的問題是什麼是一些可行的替代方案,我試圖做什麼,除了棄用之外,我的代碼特別「錯誤」。

+0

是否有你不想使用'attr_accessor'的原因? – PinnyM 2013-04-23 20:47:47

+0

有時我可能會將屬性設置爲唯一名稱,或者我會在極少數情況下使用此技術。我不確定採用這種方法有多傳統,因此我在問。 – jason328 2013-04-23 20:49:50

+0

由於廢棄狀態,這不會被支持 - 請參閱http://stackoverflow.com/questions/10596073/deprecation-warning-for-creating-attribute-currency – PinnyM 2013-04-23 20:53:35

回答

1

你可以把你User對象哈希,然後將其混合附加鍵:

class User 
    def to_hash 
     hash = {} 
     instance_variables.each {|var| hash[var.to_s.delete("@")] = instance_variable_get(var) } 
     hash 
    end 
end 

而在你的控制器:

user = User.find(1) 

user = user.to_hash 

user[:status] = "Some cool status" 

render :json => user.to_json 

PS。無論如何,無論如何都不需要使用實例變量@user,因爲本地user變量已經足夠好了。

+0

嗯。我的用戶以「{」attributes「=> {},」relation「=> nil,」changed_attributes「=> {},」previously_changed「=> {},」attributes_cache「=> {},」association_cache「=> {},「aggregation_cache」=> {},「marked_for_destruction」=> false,「destroyed」=> false,「readonly」=> false,「new_record」=> false}' – jason328 2013-04-23 21:04:41

+0

這是因爲你的'User'是ActiveRecord模型。你可以通過這種方式指定哪些實例屬性應該轉換爲json: 'user.attributes.to_json(:only => ['first_name','last_name'])' – chrmod 2013-04-23 22:28:22

+0

另一個解決方案就是寫出一個散列並做一個.to_json(尤其是如果你將要發回的數據很小) – timpone 2013-04-24 00:54:33

相關問題