I
I
Ilya Bondarenko2016-02-09 14:55:22
Ruby on Rails
Ilya Bondarenko, 2016-02-09 14:55:22

How to select all values ​​if has_many through association returns an empty array?

There are three models: Application - applications, Device - the device on which the application is allowed to be installed (just the model and brand), UserDevice - real user devices registered in the system (belongs to the Device contains the OS version and other information for statistics).

class Application < ActiveRecord::Base
  has_and_belongs_to_many :devices
  has_many :user_devices, through: :devices
end

class Device < ActiveRecord::Base
  belongs_to :manufacture, dependent: :destroy
  has_and_belongs_to_many :applications
  has_many :user_devices
end

class UserDevice < ActiveRecord::Base
  belongs_to :device
end

The customer's logic is as follows:
If Application has a Device, then install the application only on them. If not, then install everything.
I need to get a list of all real devices for which the application is available.
In the first case (the application has a limit on devices) it works without problems. How to return all registered user devices if the Application does not have Devices?
Application.find(2).user_devices

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Evgeny Danilov, 2016-02-15
@jmelkor

UserDevice.all, no?
Either I don't understand something, or it's very simple...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question