开发者

Help establishing a polymorphic relationship in the models

开发者 https://www.devze.com 2023-03-12 08:26 出处:网络
Models: class Thread < ActiveRecord::Base has_many :threaded, :through => :threaded, :foreign_key => :thread_id

Models:

class Thread < ActiveRecord::Base
  has_many :threaded, :through => :threaded, :foreign_key => :thread_id

class ThreadFeed < ActiveRecord::Base
 belongs_to :threaded, :polymorphic => true

Model Fields

Thread (id)
ThreadFeed (id, thread_id, threaded_id, threaded_type)

Problem is with:

@thread.threaded

Rails is using (threaded_id, threaded_type) as the foreign key and I want th开发者_如何学Pythonread_id to be the foreign key.


Take a look into this Railscast, Polymorphism

It will give you a better insight into how Polymorphism works.

First issue I notice is that it should be through :threadfeed, not :threaded

class Thread < ActiveRecord::Base
  has_many :threadfeeds, :as => :threaded

In the Railscast, he has:

class Comment < ActiveRecord::Base
  belongs_to :commentable, :polymorphic => true
end

class Article < ActiveRecord::Base
  has_many :comments, :as => :commentable
end

class Photo < ActiveRecord::Base
  has_many :comments, :as => :commentable
  #...
end

class Event < ActiveRecord::Base
  has_many :comments, :as => :commentable
end


The first problem is that Thread doesn't know what feed is:

class Thread < ActiveRecord::Base
    has_many :feeds, :through => :thread_feeds, :as => :feeded
    has_many :thread_feeds

class ThreadFeed < ActiveRecord::Base
     belongs_to :feeded, :polymorphic => true

The second problem is the complexity of polymorphic. Here's a great article on it: http://blog.hasmanythrough.com/2006/4/3/polymorphic-through

0

精彩评论

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