Has_and_belongs_to_many: Item Already in Collection?

I’m putting together what should be a simple app using content and
tags
using has_and_belongs_to_many for each.

create_table :contents_tags, :id => false do |t|
  t.references :content
  t.references :tag
end

When a user tries to add a new tag, I’m trying to detect if the
content already has the tag.

So … I grab the tag like this:
tag = Tag.where(“name = ?”, tag_name)

Then I’m trying:
if !@content.tags.where(:id => “#{tag.id}”).present?
but tag.id is always a huge number, like 2165404200

I only have two tags in the db right now, so the ID should be either 1
or 2
and i’ve verified those IDs in the db.

Any idea what’s going on?

Here’s the whole block of code for reference:
params[:item][:tags].each do |tag_name|
tag = Tag.where(“name = ?”, tag_name)
if !@content.tags.where(:id => “#{tag.id}”).present?
@content.tags << tag
end
end

On Apr 19, 5:24am, bergonom [email protected] wrote:

Here tag is actually an activerecord::Relation, a proxy object that
will turn into an array if needed. It already has an I’d method though
so it sounds like you’re getting back the ruby object id of the
relation rather than the database id of a tag

tag = Tag.where(…).first should work.

You could also do @content.tags.include?(tag) these days this will
either issue a query to check the presence of the single tag or, if
the association is already loaded, use the in memory array.

Fred