Ruby on rails 不同';作者';模型

Ruby on rails 不同';作者';模型,ruby-on-rails,polymorphic-associations,Ruby On Rails,Polymorphic Associations,多态关联(这里是注释)本身如何与不同类型的作者关联 从 class Comment < ActiveRecord::Base belongs_to :commentable, :polymorphic => :true end 对于多态注释模型,我想添加ID和类型以引用注释作者: create_table "comments", :force => true do |t| t.text "content" t.integer "comment

多态关联(这里是注释)本身如何与不同类型的作者关联

class Comment < ActiveRecord::Base
  belongs_to :commentable, :polymorphic => :true
end
对于多态注释模型,我想添加ID和类型以引用注释作者:

  create_table "comments", :force => true do |t|
    t.text     "content"
    t.integer  "commentable_id"
    t.string   "commentable_type"
    t.integer  "author_id"
    t.string   "author_type"
  end
“事件”页面显示评论,单击作者姓名会将我带到用户(5)或AnotherModel(2),具体取决于谁写了评论

我想知道每个人是如何处理这种情况的。我是否应该考虑添加第二个多态“中间层”,比如“profile”,它可以容纳子类“User”、“Host”等等

编辑2

只有一个用户模型显然会让这里的生活更轻松,但由于其他原因,这是不可能做到的。总的来说,我感兴趣的是如何组织好这一切。

简单地说

<%= link_to comment.author.name, comment.author %>

这是我在过去使用过的(在视图帮助器中),但它使用了eval:

def model_path(model, options = {})
    {:format => nil}.merge(options)
    format = (options[:format].nil? ? 'nil' : "'#{options[:format].to_s}'")
    eval("#{model.class.to_s.downcase}_path(#{model.id}, :format => #{format})")
end
这样使用:

<%= link_to comment.author.name, model_path(comment.author) %>

会有帮助吗


谢谢,我想您的第一个解决方案需要一个
属于:author
?只是没有作者模型。因此,使用
属于\u to:author,:class=>“User”
将启用它。但是,再次强调,我不能将评论与某个特定的作者模型(需要主机、用户等)联系起来,因此我可以这样理解:用户和主机都可以作为作者在用户和主机上创建评论吗?然后,您的评论需要一个多态作者,就像您使用:commentable.Thank一样,需要在我的脑海中确认这一点:通过=>其他用户:)谢谢,看起来是一个可能的解决方案,但请查看我的其他评论,因为
comment.author.name
需要一个专用的
属于
?(我认为blackbird的答案比我的好,evals给我heeby jeebies…)如果你的评论有作者,那么它必须与作者有关系(在这种情况下是多态的)。如果“作者”是指“评论的作者”,那么使用
评论.评论.作者
代替
评论.作者
link_to ..., action_in_host_path(comment.author) if comment.author.kind_of? Host
def model_path(model, options = {})
    {:format => nil}.merge(options)
    format = (options[:format].nil? ? 'nil' : "'#{options[:format].to_s}'")
    eval("#{model.class.to_s.downcase}_path(#{model.id}, :format => #{format})")
end
<%= link_to comment.author.name, model_path(comment.author) %>