【发布时间】: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