1

I'm having this type of search:

values = ModelName.find(:all, :conditions => ['attr_id IN (SELECT attr_id FROM srv_type_attr WHERE id IN (?))', serv_objt_attr.collect(&:stya_id)])

Witch returns me an array of needed values:

[33458, 33438]

Next i need to check if record exists with select:

serv_objt_attr.select {|array| array.stya_id == values.collect(&:attr_id).uniq}

This is an example what i'm thinking off.

So how to do it with select, so he would walk through all values witch i'm getting from values.

I know that i could to something like

values.collect(&:attr_id).uniq do |val|
serv_objt_attr.select {|array| array.stya_id == val}
end

But i do not thing that this is a good option.

Ruby 1.8.7 Rails 2.3.4

3
  • May I ask what Rails version you are using? Because Model.find(:all, :conditions => [...]) isn't a statement you come across often. Normally you'd use Model.where(...) This might be relevant for those writing answers. Commented Mar 17, 2020 at 21:17
  • @3limin4t0r Added rails version. Commented Mar 17, 2020 at 21:23
  • When looking at the first two code blocks I'd assume values is an array containing integers. I'm a bit confused by your third and fourth code block, especially values.collect(&:attr_id) which is short for values.collect { |value| value.attr_id }. An integer doesn't have the method attr_id as far as I know. What is happening here? Commented Mar 17, 2020 at 21:27

1 Answer 1

1

This is a good case for the set intersection operator:

values = ModelName.find(:all, :conditions => ['attr_id IN (SELECT attr_id FROM srv_type_attr WHERE id IN (?))', serv_objt_attr.collect(&:stya_id)])

values & Set.new(serv_objt_attr.map(&:stya_id)

Here's what the & does:

>> values = [1,2,3]
=> [1, 2, 3]
>> other_array = [1,5,9,3]
=> [1, 5, 9, 3]
>> values & other_array
=> [1, 3]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.