Rails 请教 ActiveRecord 动态注入属性的问题

wikimo · 2014年10月09日 · 最后由 heliang7 回复于 2014年10月10日 · 2768 次阅读

问题描述,直接看代码

#User( username,sex)

user = User.first 
p user 
#<User id:1 username:xxx sex:0>
#返回model  username,sex属性,如果想额外注入一个phone属性要怎么解;
#如果想返回<User id:1 username:xxx sex:0 phone:123123> 需要怎么做

通过 att_accessor 设置 phone,打印 user 的时候并不会出现 phone,通过 user.attributes 也一样,可见只能通过 clone 一份去设置,不知有别的什么办法能解决这个问题。

方案 1,migration add column,太挫; 方案 2,new_user = user.attributes 去 copy 一份,也不够优雅;

应该还有更理想的方案。

或者换一种说法 User has_many addresses 打印 user 的时候希望一并把 addresses 也都带上一次输出。

Google 了一会没结果(关键词 activerecord dynamic add attributes 等),基础没学好,实在抱歉,谢谢!

楼主只是为了打印的时候多显示些么? 一般都是直接定义方法,需要的时候调用就行了。

根据你的需求,我建议重写 inspect 方法...

# Returns the contents of the record as a nicely formatted string.
def inspect
  # We check defined?(@attributes) not to issue warnings if the object is
  # allocated but not initialized.
  inspection = if defined?(@attributes) && @attributes
                 self.class.column_names.collect { |name|
                   if has_attribute?(name)
                     "#{name}: #{attribute_for_inspect(name)}"
                   end
                 }.compact.join(", ")
               else
                 "not initialized"
               end
  "#<#{self.class} #{inspection}>"
end

#1 楼 @heliang7 返回 json 的时候,如果 @user.to_json,那么子类数据不会被输出,希望子类数据也一并输出,所以希望通过对 model 注入一个虚拟属性去实现

补充: 这样的话行也行,另外定义方法知道如何实现,想了解下没有更简单的方法。

#2 楼 @saiga 谢谢回复,结合 1 楼回复,大概知道解法了,实现部分可以参考你的方法。

#3 楼 @wikimo 这个建议在 json builder 里面处理,比如 rabl 或 jbuilder

@saiga 受教了,这样的处理方法更好些,3Q 😄

直接用:include 就可以了。

user.to_json(:include => :phones)
需要 登录 后方可回复, 如果你还没有账号请 注册新账号