【问题标题】:Help establishing a polymorphic relationship in the models帮助在模型中建立多态关系
【发布时间】:2011-06-09 21:57:59
【问题描述】:

型号:

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 使用 (thread_id, threaded_type) 作为外键,我希望 thread_id 作为外键。

【问题讨论】:

  • 嗯...通过关系进行多态可能会变得棘手。你能描述更多关于你正在尝试做的事情吗?

标签: ruby-on-rails ruby-on-rails-3 polymorphism polymorphic-associations


【解决方案1】:

看看这个 Railscast,Polymorphism

它将让您更好地了解多态性的工作原理。

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

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

【讨论】:

  • 你看完了吗?它讨论了所有模型的关联。你有 join 模型,它属于_to: 线程?
  • 更新更多细节。这有帮助吗?
  • 谢谢,但这不起作用。在我现在看到的日志中:'ActiveRecord::StatementInvalid: SQLite3::SQLException: no such column: thread_feeds.threadfeeds_id: SELECT "thread_feeds".* FROM "thread_feeds" WHERE ("thread_feeds".threadfeeds_id = 77 AND "thread_feeds". threadfeeds_type = '墙')'
  • 我希望只有 where 列 (thread_id = 77) 不知道为什么类型“墙”仍然存在我不想要那个。想法?
【解决方案2】:

第一个问题是 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/polymorphic-through

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-07
    相关资源
    最近更新 更多