Ruby如何将模型关联分配给多个模型对象

时间:2017-01-25 09:16:42

标签: ruby-on-rails ruby associations

我已经查看了问题,并且只知道如果我想将对象分配给多个模型(多态),该怎么做。基本上,我有两个模型(日和日程表),我想与一个关联连接。问题是我希望有几天可以有一个时间表: (day1.schedule == schedule1,day2.schedule == schedule1)

我正在使用多态关联(我认为这是我试图做的),并且它正在工作,但我发现每次我将日程安排分配给每天时,它都会将日信息分配给可映像的日程表: (schedule1.imageable == day2,schedule1.imageable_id == day2.id,schedule.imageable_type == Day)

这是不必要的信息(如果一天不再存在,那将是不正确的)我不想要保存时间表,但如果我删除为::imageable,它会中断,我可以&#39 ; t。

我基本上需要单向关联,而且我还没有弄清楚如何设置一个。我希望Days保存计划,但计划不保存任何天数。是否存在关联,或者我将被迫使用Schedule id?

class Day < ApplicationRecord**

    has_one :schedule, as: :imageable

    validates :day, presence: true

    def after_initialize( args = {} )
        @day = args[:day]
        @schedule = args[:schedule]
    end
end

我的Schedule课程中没有与Day有任何关系。它会自动创建一个imageable_id和imageable_type方法(虽然我 必须在我的数据库中为它创建列)

1 个答案:

答案 0 :(得分:0)

如果我理解正确,您只需要Schedule has_many :days

class Schedule < ApplicationRecord
  has_many :days
end

class Day < ApplicationRecord
  belongs_to :schedule
end

这样,Schedule不会保存days的任何内容:有关该关系的信息将保存在schedule_id表的days列中。

这是相应的documentation