Rails3.2中在模型对象总写入自定义属性问题

浏览:922 发布日期:2015-12-12 15:24:09

有如下代码:

class PostComment < ActiveRecord::Base
  attr_accessible :comment_id, :comment_type, :content, :email, :name, :post_id, :status

  #获得树形评论结果
  def self.getCommentTreeByCommentId(commentId, postId)
    topComments = self.where("comment_id = ? and post_id = ?", commentId, postId)

    (0..(topComments.length - 1)).each do |i|

        t = self.getCommentTreeByCommentId(topComments[i].id, postId)

        topComments[i][:child] = t if t.length > 0
    end

    topComments
  end

end

数据库中并没有child字段,Rails会提示 DEPRECATION WARNING: You're trying to create an attributechild'. Writing arbitrary attributes on a model is deprecated. Please just useattr_writer` etc.

而且如果输出结果,发现并没有child,但是,如果result[0][:child][0],你是可以访问到的,==!。

从那个flow网站,跳到github的源码,如下:

if column || @attributes.has_key?(attr_name)
-          @attributes[attr_name] = type_cast_attribute_for_write(column, value)
-        else
-          raise ActiveModel::MissingAttributeError, "can't write unknown attribute `#{attr_name}'"
+        unless column || @attributes.has_key?(attr_name)
+          ActiveSupport::Deprecation.warn(
+            "You're trying to create an attribute `#{attr_name}'. Writing arbitrary " \
+            "attributes on a model is deprecated. Please just use `attr_writer` etc."
+          )
         end
+
+        @attributes[attr_name] = type_cast_attribute_for_write(column, value)
       end
       alias_method :raw_write_attribute, :write_attribute

虽然它给出了警告,但还是写入了对象中,,虽然p obj,你看不到你写入的自定义属性吧。