Ruby on rails 确保模型与同一父级关联

Ruby on rails 确保模型与同一父级关联,ruby-on-rails,ruby,Ruby On Rails,Ruby,假设我有3个相互关联的模型: class Farm < ApplicationRecord has_many :horses has_many :events end class Horse < ApplicationRecord belongs_to :farm has_many :events_horses, class_name: 'Event::EventsHorse' has_many :events, through: :events_horses,

假设我有3个相互关联的模型:

class Farm < ApplicationRecord
  has_many :horses
  has_many :events
end

class Horse < ApplicationRecord
  belongs_to :farm
  has_many :events_horses, class_name: 'Event::EventsHorse'
  has_many :events, through: :events_horses, source: :event, dependent: :destroy
end

class Event
  belongs_to :farm
  has_many :events_horses, class_name: 'Event::EventsHorse'
  has_many :horses, through: :events_horses, source: :horse, dependent: :destroy
end

class Event::EventsHorse < ApplicationRecord
  self.table_name = "events_horses"

  belongs_to :horse
  belongs_to :event

  audited associated_with: :event, except: [:id, :event_id]
end

我认为您使用的模型在需要一致性检查的表之间设置了太多id

如果以这种方式设置模型,则无需验证马场和事件是否一致,因为数据可确保:

class Farm < ApplicationRecord
  has_many :horses
  has_many :events
end

class Horse < ApplicationRecord
  belongs_to :farm
  has_many :events, through: :farm
end

class Event < ApplicationRecord
  belongs_to :farm
  has_many :horses, through: :farm
end

顺便说一句,您是否有
Event::EventsHorse
而不是简单地为
EventsHorse
建立一个单独的模型?

我已经修复了它。应该是活动。谢谢你的帮助!我实际上简化了这个问题,使之更容易理解。我已经有了“has many through”
has_many:events_horse,class_name:“Event::EventsHorse”has_many:horse,through::events_horse,source::horse,dependent::destroy
我需要“events_horse”作为其他用途,但我不知道如何实现这一点。@irondnb请更新(编辑)您的原始问题与您拥有的实际代码,包括您的事件马模型,并改写您的问题,使其询问您真正希望了解的内容。否则,它是非常不清楚的,其他读者不会看到你的意图。我的直觉是,我的答案仍然适用,但添加了一些细节。
具有且属于多个
使“事件马”关系隐式化,但您希望它显式化。看一看:。我确实理解差异,我需要通过
了解很多(可以解释原因)抱歉给您带来不便,但这是我在这里的第二个问题。我已经更新了问题代码。我的问题仍然与问题有关。谢谢你解决我的问题,但我不明白你最后一个关于
Event::EventsHorse
的问题。我喜欢给我的模型命名,但如果你问为什么很多人都通过habtm——这是跟踪asociacion删除()所必需的,它只适用于
有许多通过
@irondnb您正在为
事件设置名称空间
一个
事件
名称空间,但是
事件
事件
的偏见似乎没有比对
更大。我想这有点随意,因为你可以把它命名为
Horse::EventsHorse
。您没有为
事件
模型命名名称空间
EventsHorse
正好介于两者之间,彼此之间的关系不强。这没什么害处,我只是好奇你为什么那样做。
class Farm < ApplicationRecord
  has_many :horses
  has_many :events
end

class Horse < ApplicationRecord
  belongs_to :farm
  has_many :events, through: :farm
end

class Event < ApplicationRecord
  belongs_to :farm
  has_many :horses, through: :farm
end
class Event::EventsHorse < ApplicationRecord
  ...
  validate :horse_belongs_to_farm

  private

  def horse_belongs_to_farm
    horse.farm_id == event.farm_id 
  end   
end