Rails ActiveRecord scope with multiple conditions -


i have rails app have unit model , status model. status has_many units , unit belongs_to status.

i wrote scope on unit find of units specific status, "in service" so:

scope :in_service, lambda { where(status_id: status.find_by_unit_status("in service").id)} 

this allows me call unit.in_service.count count of units in service.

but want write scope allow me scope out units status of in service, @ post, , @ station accurate view of units since these other 2 statuses considering unit available.

i'm not sure how write this. scope contains multiple conditions or data fields.

can lend hand?

update

i tried writing class method called available this:

  def self.available     unit.where(status_id: status.find_by_unit_status("in service").id)     .where(status_id: status.find_by_unit_status("at post").id)     .where(status_id: status.find_by_unit_status("at station").id)   end 

i'm not sure if method i'm looking since want find units each of these statuses. think wrote might constraining method unit must have of these statuses.

you've got couple things going on here. first if want find units status 1 of many, you'll need pass array so:

scope :in_service, lambda { where(status_id: status.where(unit_status: ["in service", "at post", "at station"]).map(&:id))} 

second, in updated method example, you're chaining bunch of where clauses together, result in each 1 joined and.


Comments

Popular posts from this blog

javascript - Jquery show_hide, what to add in order to make the page scroll to the bottom of the hidden field once button is clicked -

javascript - Highcharts multi-color line -

javascript - Enter key does not work in search box -