【问题标题】:Best Way to Create attributes for a Model Instance Object为模型实例对象创建属性的最佳方式
【发布时间】:2013-04-23 20:44:05
【问题描述】:

我正在为 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 的对象同样容易。

我的问题是,除了弃用之外,我的代码有哪些可行的替代方案,以及我的代码有哪些特别“错误”的地方。

【问题讨论】:

  • 您是否有不想使用attr_accessor的原因?
  • 有时我可能会将属性设置为一个唯一的名称,或者我会在极少数情况下使用这种技术。我不确定使用这种方法有多传统,因此我要问。
  • 作为弃用状态,这不会被支持 - 请参阅stackoverflow.com/questions/10596073/…
  • 是的,我知道。但是不写后端组件就很好了,因为它是任意使用和有用的东西。

标签: ruby-on-rails ruby ruby-on-rails-3 model


【解决方案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

附言。无论如何,在渲染 json 时无需使用实例变量 @user,本地 user 变量就足够了。

【讨论】:

  • 嗯。我的用户返回 {"attributes"=>{}, "relation"=>nil, "changed_attributes"=>{}, "previously_changed"=>{}, "attributes_cache"=>{}, "association_cache"=>{}, "aggregation_cache"=>{}, "marked_for_destruction"=>false, "destroyed"=>false, "readonly"=>false, "new_record"=>false}
  • 因为你的User是ActiveRecord模型。您可以通过这种方式指定哪些实例属性应转换为 json:user.attributes.to_json(:only => ['first_name','last_name'])
  • 另一种解决方案是写出一个哈希并在其上执行一个 .to_json 尤其是如果您要发回的数据很小
猜你喜欢
  • 1970-01-01
  • 2014-01-17
  • 2012-01-10
  • 1970-01-01
  • 2011-12-27
  • 2017-10-16
  • 2013-10-15
  • 2012-04-06
  • 1970-01-01
相关资源
最近更新 更多