has_and_belongs_to_many: Item Already in Collection?

7 views
Skip to first unread message

bergonom

unread,
Apr 18, 2012, 5:24:04 PM4/18/12
to Ruby on Rails: Talk
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

Frederick Cheung

unread,
Apr 19, 2012, 12:27:12 AM4/19/12
to Ruby on Rails: Talk


On Apr 19, 5:24 am, bergonom <jbergh...@yahoo.com> wrote:
>
> When a user tries to add a new tag, I'm trying to detect if the
> content already has the tag.J
>
> 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, like2165404200
>
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
> 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
Reply all
Reply to author
Forward
0 new messages