0

What I'm trying to do
In my Model, I want to select only the items that are NOT equal to (a or b) to. So I did this which works.

# This works
select { | item | item.attribute != a}.select {| item | item.attribute != b}

Question
This chaining works, but is there a another way of writing this ?
What happens if I wanted to also check c and d ? Would I add some array somewhere ?
I wouldn't keep chaining would I ?

Follow Up Question
The select line will work in my model, but when I try to put the reject line in my model I get a undefined method reject for #<Class>

class Model < ActiveRecord::Base

def self.foo
arr = [a,b]
reject { | item | arr.include?(item.attribute)}
end

end

I'm guessing ActiveRecord does not understand reject ? Does ActiveRecord have a method that is similar to SQL NOT LIKE ?

alenm
  • 1,013
  • 3
  • 15
  • 34
  • I'm not so familiar with ActiveRecord, so hopefully someone can help you more with that more. – Paul Hoffer Mar 05 '11 at 16:16
  • You have to call `reject` on some array of ActiveRecord objects. From what do you intend to reject? For example in phoffers code, heis rejecting from `items`. You have to define this somewhere and call `reject` on it. – rubyprince Mar 05 '11 at 18:27

1 Answers1

2

We'll say that items is your array of items that you are using #select on.

arr = [a, b] # or [a, b, c, d]
items.reject { |item| arr.include?(item.attribute) }

This reverses your select into reject, but rejects the items that ARE equal to (a or b).

Paul Hoffer
  • 12,606
  • 6
  • 28
  • 37
  • This works! The only question I have is for some reason I cannot get this to work in my Model. – alenm Mar 05 '11 at 15:40
  • What is the full code you have in your model? Note, this does not change `items`, you would have to do either `new_items = items.reject...` or do `items.reject!`. `#reject!` modifies the original array. – Paul Hoffer Mar 05 '11 at 15:46
  • My model is an ActiveRecord model. – alenm Mar 05 '11 at 15:54
  • Write `all.reject` to convert it into an array first. However you might reconsider writing your code depending on how many models you will have in your DB. This should better be an SQL query. – Marcel Jackwerth Mar 05 '11 at 15:58
  • To convert it into array is not working right. I think your right I probably need to create some SQL query for this. I'll do some research. – alenm Mar 05 '11 at 16:40