has_many:通过混淆

问题描述:

我一直在寻找其他问题/答案,但找不到任何有帮助的东西。我有userseventsstatic_events。我现在想介绍一个scheduleusers保存两种不同类型的“事件”has_many:通过混淆

我越来越挂在组织关联。具体将eventsstatic_events与特定的:foreign_key关联以创建schedule。这是我的第一个应用程序,所以事情还是有点新的。一如既往,任何帮助将不胜感激。以下是我迄今为止:

型号:

class User < ActiveRecord::Base 
    has_many :events, :through => :schedules, :source => "followed_id" 
    has_many :static_events, :through => :schedules, :source => "followed_id" 
end 

class Event < ActiveRecord::Base 
    belongs_to :users 
    belongs_to :schedules, :foreign_key => "followed_id" 
end 

class StaticEvent < ActiveRecord::Base 
    belongs_to :users 
    belongs_to :schedules, :foreign_key => "followed_id" 
end 

class Schedule < ActiveRecord::Base 
    belongs_to :users 
    has_many :events 
    has_many :static_events 
end 

数据架构:

create_table "schedules", 
t.integer "followed_id" 
end 

create_table "users", 
    t.string "name" 
    t.string "email" 
    t.datetime "created_at" 
    t.datetime "updated_at" 
end 

create_table "events", 
    t.string "content" 
    t.integer "user_id" 
    t.datetime "created_at" 
    t.datetime "updated_at" 
    #several more fields left out for brevity 
end 

create_table "static_events", 
    t.string "content" 
    t.integer "user_id" 
    t.datetime "created_at" 
    t.datetime "updated_at" 
    #several more fields left out for brevity 
end 

我要对这个以最有效的方式?

你的代码没问题。但是,目前尚不清楚为什么你有两种不同的型号EventStaticEvent。在你的移植中,他们似乎有相同的字段。这似乎是single-table inheritance的好例子。在那种情况下你Event模式将保持不变,但StaticEvent应该是这样的:

class StaticEvent < Event 
    # ... 
end 

Event,而不是直接从ActiveRecord::Base继承。这意味着它获得了所有Event的行为,但您也可以只定义特定于StaticEvent的方法和变量。

对于单表继承,您将不具有static_events表,但您的events表将具有附加字符串字段type。其余部分将由Rails来完成。

然而,如果StaticEvent没有从除Event不同的任何方法或变量“这是一个静态的,”你不认为你有更多的在未来,它会更有意义为两者使用Event并给它一个带有布尔类型的is_static字段。在这种情况下,您Schedule模型是这样的:

class Schedule < ActiveRecord::Base 
    # ... 

    has_many :events,  :conditions => { :is_static => false } 

    has_many :static_events, :conditions => { :is_static => true }, 
          :class_name => 'Event' 
end 

这样每个协会都有自己的名字(eventsstatic_events),但它们指的是同一型号(:class_name => 'Event')。唯一的区别是条件,它指定其中Event记录是该关联的一部分。这也可以让你免费做Schedule.static_events.create ...Schedule.static_events.where(...).first等。

而且最后,你说你“现在要为大家介绍的时间表,为用户节省了两种不同类型的‘事件’。”如果这是你创建的Schedule模块,你应该简单地丢弃Schedule唯一原因模型并直接在User上定义上述关联。除非它有自己的属性和/或方法,否则不需要额外的Schedule模型。

+0

约旦,我的错误 - 我更新了代码,他们确实有几个不同的领域。这就是说,我认为单表继承仍然是一条可行的路。除此之外,在':foreign_key'上用''用户'加入'Event'和'StaticEvent'确定并且不会引起任何问题? – Alekx 2012-01-27 03:55:57

+0

'Schedule'的用途是什么?这是否意味着它是一个独立的类,或者它仅仅是用户和他们保存的事件之间的映射(在这种情况下,“Scheduling”或“Attending”可能是更好的名称)。 – 2012-01-27 04:56:50

+0

好的电话,'出席'是一个更好的名字。它意味着用户和他们保存的事件之间的映射。但是在思考之后,我需要将'Event'和'StaticEvent'作为独立的模型,因为它们会有太多不同的信息。还有可能需要创建其他模型并添加到“参加”。鉴于此,我的原始代码/逻辑是否仍然适用,将'Schedule'的名称更改为'Attending'? – Alekx 2012-01-27 16:22:43