0

我正在开发一个简单的应用程序,该应用程序允许用户写一篇文章(parent_post),另一个用户回答这篇文章(child_post)。我正在使用Ancestry gem来跟踪帖子之间的关系。Ancestry 是一个 gem/插件,它允许将模型的记录组织为树结构(或层次结构)。它公开了所有标准的树结构关系(父、根、子、祖先……)。

应用程序的数据库 schema.rb:

 create_table "posts", :force => true do |t|
    t.text     "title"
    t.text     "content"
    t.datetime "created_at",         :null => false
    t.datetime "updated_at",         :null => false
    t.integer  "user_id"
    t.string   "ancestry"
  end

  create_table "users", :force => true do |t|
    t.string   "email",                  :default => "", :null => false
    t.string   "encrypted_password",     :default => "", :null => false
    t.string   "reset_password_token"
    t.datetime "reset_password_sent_at"
    t.datetime "created_at",                             :null => false
    t.datetime "updated_at",                             :null => false
    t.string   "name"
  end

挑战: 我想在 child_post 的显示视图中显示有关 parent_post 的作者的信息。通过 Ancestry gem,您可以调用“父级”并处理帖子表中的所有列。帖子表(见上文)有一个 user_id 列,所以我可以调用

@post.parent.user_id

向我展示有效的用户 ID。但我想显示用户名而不是 user_id。

当然,user_id 和 username (name) 是通过 users 表连接的(参见上面的 schema.rb),但是我如何在这里解决它们呢?@post.parent.user_id.name 不起作用。

型号:

class User < ActiveRecord::Base
has_many :posts
end

class Post < ActiveRecord::Base
has_ancestry
belongs_to :user
end

我对 Rails 还是很陌生,并被困在这里。有没有我没有看到的超级简单的解决方案?

非常感谢您的帮助!

4

1 回答 1

0

How about @post.parent.user.name? I recommend making this a method on the Post model rather than your view or controller. Call it @post.original_poster_name or similar.

于 2013-11-29T03:38:11.257 回答