【问题标题】:Polymorphic association confusion, get resource through association多态关联混淆,通过关联获取资源
【发布时间】:2012-02-13 12:28:21
【问题描述】:

我在这里可能完全糊涂了。

我有一个事件模型,它有一个属于事件的时间线。 Timeline 有_many TimelineItems 属于_to Timeline。

def Event
  has_one :timeline
end

def Timeline
  belongs_to :event
  has_many :timeline_items
end

def TimelineItem
  belongs_to :timeline
end

create_table :admin_timeline_items do |t|
  t.references :admin_timeline
  t.references :user
  t.references :resource, :polymorphic => true
  t.string :method
end

因此,通过 TimelineItem 对象,我将能够生成例如以下输出:

eml 在 [DATE] 创建了帖子“Hi this is from eml”

标题“Hi this is from eml”将来自 Post 对象的 .title。所以例如。这个 TimelineItem 有这些设置

item.user = User.where(:username => "eml")
item.resource_type = "Post"
item.resource_id = 1
item.created_at = 27/082...13:37

所以问题在于获取所说的 Post 对象,或者更确切地说是获取此特定关联的正确语法。对我来说似乎非常简单,但我没有找到正确编写它所需的信息。

感谢您的帮助和时间。

【问题讨论】:

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


    【解决方案1】:

    对不起...我只是让自己感到困惑,因为我在自己的测试项目中将 resource_id 设置为错误值。我的第一个猜测是正确的。很简单:

    class TimelineItem < ActiveRecord::Base
      belongs_to :timeline
      belongs_to :user
      belongs_to :resource, :polymorphic => true
    end
    

    像这样访问资源:

    TimelineItem.first.resource
    => Post(....)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多