Rails:has_many 通过多态关联 - 这会起作用吗? [英] Rails: has_many through with polymorphic association - will this work?

查看:11
本文介绍了Rails:has_many 通过多态关联 - 这会起作用吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个 Person 可以有多个 Events,每个 Event 可以有一个多态的 Eventable 记录.如何指定 PersonEventable 记录之间的关系?

A Person can have many Events and each Event can have one polymorphic Eventable record. How do I specify the relationship between the Person and the Eventable record?

这是我拥有的模型:

class Event < ActiveRecord::Base
  belongs_to :person
  belongs_to :eventable, :polymorphic => true
end

class Meal < ActiveRecord::Base
  has_one :event, :as => eventable
end

class Workout < ActiveRecord::Base
  has_one :event, :as => eventable
end

主要问题涉及Person 类:

class Person < ActiveRecord::Base
  has_many :events
  has_many :eventables, :through => :events  # is this correct???
end

我是说 has_many :eventables, :through =>:events 就像我上面做的那样?

Do I say has_many :eventables, :through => :events like I did above?

或者我必须像这样拼写出来:

Or do I have to spell them all out like so:

has_many :meals, :through => :events
has_many :workouts, :through => :events

如果你看到一种更简单的方法来完成我所追求的事情,我会全神贯注!:-)

If you see an easier way to accomplish what I'm after, I'm all ears! :-)

推荐答案

你要做的:

class Person < ActiveRecord::Base
  has_many :events
  has_many :meals, :through => :events, :source => :eventable,
    :source_type => "Meal"
  has_many :workouts, :through => :events, :source => :eventable,
    :source_type => "Workout"
end

这将使您能够做到这一点:

This will enable you to do this:

p = Person.find(1)

# get a person's meals
p.meals.each do |m|
  puts m
end

# get a person's workouts
p.workouts.each do |w|
  puts w
end

# get all types of events for the person
p.events.each do |e|
  puts e.eventable
end

这篇关于Rails:has_many 通过多态关联 - 这会起作用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆