Rails 中不同“作者”的多态关联型号
多态关联(此处:评论)本身如何与不同类型的作者相关联?
从……开始
class Comment < ActiveRecord::Base
belongs_to :commentable, :polymorphic => :true
end
,我需要有一位作者来自模型Hosts,ID 5,另一位作者来自Users,2。
路径助手会是什么样子
<%= link_to comment.author.name, user_path(comment.author) %>
当“user_path”或“host_path”是动态的(取决于作者模型)时,
? 编辑***
有事件、地点等可以有这样的评论:
has_many :comments, :as => :commentable
对于多态评论模型,我想添加 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
事件页面显示评论,然后单击作者姓名应该将我带到 User(5) 或 AnotherModel(2),具体取决于评论的作者。
我想知道大家遇到这种情况都是怎么处理的。我是否应该考虑添加第二个多态“中间层”,例如“配置文件”,它可以容纳子类“用户”、“主机”等?
编辑2
仅拥有一个用户模型显然会让这里的生活变得更轻松,但由于其他原因而无法做到这一点。总的来说,我感兴趣的是如何很好地组织这一切。
How would a Polymorphic Association (here: Comments) be itself associated with different types of Authors?
Starting from …
class Comment < ActiveRecord::Base
belongs_to :commentable, :polymorphic => :true
end
… I'd need to have one author being from model Hosts, ID 5 and another one from Users, 2.
How could path helpers look like…
<%= link_to comment.author.name, user_path(comment.author) %>
… when "user_path" or "host_path" are dynamic, depending on the author model?
EDIT***
There are Events, Places etc. that can have comments like so:
has_many :comments, :as => :commentable
To the polymorphic Comment model i would like to add IDs and Types to refer to Authors of comments:
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
An Events page displays comments, and clicking on an author name should take me either to User(5) oder AnotherModel(2), depending on who wrote the comment.
I'd like to know how everybody handles this kind of situation. Should I think about adding a second polymorphic "middle layer", such as "profile", that could hold the subclasses "User", "Host" and so forth?
EDIT 2
Having only one User model would make life easier here obviously, but that cannot be done for other reasons. And in general i'm interested how this could be organized well.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
简单地说
应该可以解决问题。如果您想要更大的灵活性,我建议
Simply putting
should do the trick. If you want more flexibility, I would suggest
这是我过去使用过的(在视图助手中),但它使用了 eval:
像这样使用:
This is what I've used in the past (in a view helper), but it uses an eval:
Use like this:
polymorphic_url 有帮助吗?
Would polymorphic_url help?