如何在Rails 3.1中分配对象的新元素?

时间:2012-01-17 19:19:18

标签: ruby-on-rails-3 variable-assignment

@comments = []

@preComments = Comment.where(:resource_hash => resource_hash).
                       sort(:created_at.desc).all

@preComments.each do |comment|
  newComment = comment
  u = ::User.find_by_id comment.user_id

  newComment.display_name = "Some name"

  if u.image_location.nil?
    newComment.image_location = "defaultpic"
  else
    newComment.image_location = u.image_location
  end

    p u

    @comments << newComment

    p "HERE!!!!!"
  end

这是我的代码,但我收到错误说

undefined method `display_name=' for #

那么如何分配display_name

1 个答案:

答案 0 :(得分:1)

披露:我从未使用过MongoMapper

所以我最好的选择是:只需添加display_name作为Comment架构的一部分。在models / comment.rb中:

class Comment
  include MongoMapper::Document

  key :display_name,  String
  key ...
  [...]