2013-04-23 108 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

相关问题