开发者

Polymorphic Associations in Rails for different 'author' models

How would a Polymorphic Association (here: Comments) be itself associated with开发者_如何学Go 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.


Simply putting

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

should do the trick. If you want more flexibility, I would suggest

link_to ..., action_in_host_path(comment.author) if comment.author.kind_of? Host


This is what I've used in the past (in a view helper), but it uses an 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

Use like this:

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


Would polymorphic_url help?

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜