Association.contains

Good evening all,

I’m looking to do something similar to the following (pseudo code) - and
I’m sure there’s got to be a way to do this in rails w/o writing some
verbose logic:

tag = Tag.new(‘foo’)

if !article.tags.contains(tag) then
article.tags << tag
article.save
end

It’s the contains piece I’m after. For some reason, I don’t relaly
want to write if !article.tags.find(tag.id) then…but that might be my
only bet.

Once you have your tag object…

article.tags << tag unless article.tags.include?(tag)

But - I’m not sure if the object-object comparison that include?
performs is what you’re really after.

c.

Cory wrote:

Good evening all,

I’m looking to do something similar to the following (pseudo code) - and
I’m sure there’s got to be a way to do this in rails w/o writing some
verbose logic:

tag = Tag.new(‘foo’)

if !article.tags.contains(tag) then
article.tags << tag
article.save
end

It’s the contains piece I’m after. For some reason, I don’t relaly
want to write if !article.tags.find(tag.id) then…but that might be my
only bet.

You can use include? to check if an item already exists in an array:

a = [1,2,3]
a.include?(3) # => true

-Jonathan.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs