【问题标题】:how to give query in has_many through association Rails如何通过关联 Rails 在 has_many 中进行查询
【发布时间】:2015-07-03 12:51:08
【问题描述】:

我有以下关联

Mobile.rb
has_many :mobile_networks, :dependent => :destroy

has_many :networks, :through => :mobile_networks

Network.rb
has_many :mobiles, :through => :mobile_networks


MobileNetwork.rb
belongs_to :mobile
belongs_to :network

我想查询手机的所有 mobile_networks,然后我想检查所有网络是否处于活动状态,就像我在我的助手中编写了这段代码一样,我正在获得移动

    def mobile_state(mobile)
      mobile.mobile_networks.each do |e|
        e.network.is_checked #true
      end
   end

所以我需要在查询中执行此操作。请指导我如何做到这一点。

【问题讨论】:

  • mobile.networks.map(&:is_checked) 试试这个
  • 如果 mobile.networks.where(:ischecked =true)end 这样的事情我需要一个条件
  • Mobile.includes(:networks).where(id: params[:id]).where('is_checked = ?', true) Mobile.includes(:networks).where(id: params[:id], networks: {is_checked: true})
  • 不工作它给我错误 ActionView::Template::Error (undefined method `includes' for #<0xddfdbf0>

标签: ruby-on-rails rails-activerecord has-many-through


【解决方案1】:

您可以执行以下操作:

Mobile.joins(:networks).where(id: params[:id]).each do |m|
  m.networks.map(&:is_checked?)
end

【讨论】:

  • 我认为他只想要所有的网络,并且在查询之后,他想检查每个网络是否被检查。如果是这样,只需删除 where 条件并使用应该有效的问题的帮助器。
  • @codingaddicted lmk 如果你认为这就是他的意思。你似乎比我更了解这个问题的含糊性。
  • 提问的艺术很复杂。尽管如此,即使它看起来很简单,我也不确定是否理解它!我投票赞成这项努力。
【解决方案2】:
MobileNetwork.mobiles(params[:id]).joins(:network).merge(Network.checked)

class Network < ActiveRecord::Base
  scope :checked -> {
    where(is_checked: true)
  }
end

class MobileNetwork < ActiveRecord::Base
  scope :mobiles, ->(*m) {
    where(mobile_id: m.flatten.compact.uniq)
  }
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多