user4827489
user4827489

Reputation:

how to give query in has_many through association Rails

I have following association

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

I want to query all mobile_networks of mobile and after that I want to check all network whether it is active or not something like I have written this code in my helper where I am getting mobile

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

So i need to do this in a query. Please guide me how to do this.

Upvotes: 0

Views: 40

Answers (2)

ilan berci
ilan berci

Reputation: 3881

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

Upvotes: 0

Collin Graves
Collin Graves

Reputation: 2267

You could do the following:

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

Upvotes: 1

Related Questions