帮助在模型中建立多态关系

发布于 2024-11-14 19:00:25 字数 511 浏览 3 评论 0原文

模型:

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

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

模型字段

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

问题在于:

@thread.threaded

Rails 使用 (threaded_id, threaded_type) 作为外键,而我希望 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 thread_id to be the foreign key.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

云淡风轻 2024-11-21 19:00:25

看看这个 Railscast,多态

它会让你更好地了解多态是如何工作的。

我注意到的第一个问题是它应该通过 :threadfeed,而不是 :threaded

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

在 Railscast 中,他有:

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

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
池木 2024-11-21 19:00:25

第一个问题是Thread不知道feed是什么:

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

第二个问题是多态的复杂性。这是一篇关于它的精彩文章: http://blog.hasmanythrough.com/2006/ 4/3/多态贯通

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文