【问题标题】:How do I get the belongs_to association from a has_many association如何从 has_many 关联中获取 belongs_to 关联
【发布时间】:2014-05-26 23:01:52
【问题描述】:

我有许多关联的模型,但我不确定如何获得通过所有模型的关联。

Trip.rb
  has_many :itineraries
  has_many :services, :through => :itineraries


Itinerary.rb
  belongs_to :Service

  def selected
    # can be true or false
  end


Service.rb
  has_many :itineraries

如果我只是想要Service 的完整列表,我可以致电@trip.services。然而,我想要的只是来自Itinerariess 的服务列表被选中。我可以运行 @trip.itineraries.pluck(:service) 但它只返回一个普通的旧数组。是否可以通过这种方式获得Services 对象的 AR 关联?

【问题讨论】:

  • 你写了has_many :bees。你的bees模型在哪里?而且不是has_many :chas_many应该用复数形式。就像has_many :products一样。
  • 模型实际上是 Trip、Itinerary 和 Service。我已经更新了我的演示代码以反映这一点。
  • abc的类型是什么?
  • @tamer,我不明白。这个问题是关于底部段落的吗?那些abc 引用也被更改以反映它们的模型。

标签: ruby-on-rails rails-activerecord


【解决方案1】:

好吧,如果我理解你,你可以这样做:

@trip.services.where(itinerary_id: your_selected_itineraries.ids)

没有尝试过这段代码,因为我离我的 Rails 机器不近,但我认为它应该可以工作。

【讨论】:

  • 里面的“your_selected_itineraries”是什么?那是一种方法吗?住在旅途中?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多