【问题标题】:Rails: Trouble With Model Association Using Ancestry Gem (Tree Structur Model)Rails:使用 Ancestry Gem 的模型关联问题(树结构模型)
【发布时间】:2013-11-28 21:21:31
【问题描述】:

我正在开发一个简单的应用程序,该应用程序允许用户撰写帖子 (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 还是很陌生,所以卡在这里。有没有我没有看到的超级简单的解决方案?

非常感谢您的帮助!

【问题讨论】:

    标签: ruby-on-rails-3 tree associations model-associations ancestry


    【解决方案1】:

    @post.parent.user.name 怎么样?我建议将此作为 Post 模型上的方法,而不是您的视图或控制器。称它为@post.original_poster_name 或类似名称。

    【讨论】:

    • 完美!我知道,一个简单的。天哪。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多