0

I'm creating a tag system right now where Post has_many :tags, :through => :tag_joins

Right now when a new tag is created, a join is automatically created, connecting the tag and post the tag was created on. The problem is I'm trying to use before_create to check if a tag with the same name and user ID has already been created. If it has already been created, I'd like the join to use the original tag ID, instead of letting it create a new tag ID.

Any tips for how I can accomplish this?

1
  • I'm just curious, standard Rails convention would be to name join table 'posts_tags'. You just didn't like the name? And do you have any additional fields in the table besides post_id and tag_id? I just can't imagine what that could be. Commented Feb 12, 2011 at 15:47

3 Answers 3

2

Why don't you use find_or_create_by_user_id_and_tag_id() or find_or_initialize_by_.

Update

So if you want to avoid creating duplicate tags, you can just use:

@post.tags.find_or_create_by_name('tag_name')

or if you want to apply some changes before saving the new object then use

@post.tags.find_or_initialize_by_name('tag_name')

In both cases the name attribute will be set to 'tag_name' by default.

So this method will return you the tag if exists, otherwise creates it, so you can use this when you set up your join model.

Update 2

This is actually not gonna work with has_many :through, you can see a similar problem and a workaround here: Error while using `find_or_create_by` on a `has_many` `through` association

Sign up to request clarification or add additional context in comments.

Comments

1

Can't you run a private method in your model using :before_save?

If you put code like:

:before_save :method_to_check_something

...you will be able to run any manner of validation in the model without getting the controller involved (and thereby adhering to the skinny controller, fat model methodology).

1 Comment

I don't see how before_save would work? I don't want tags to be created if duplicates already exist. Isn't save kind of after the fact in regards to the join table?
0

This should take care of duplicate records between the Post and the Tag but not sure how your associations are set up with the User.

class Post < ActiveRecord::Base
  has_many :tags, :through => :tag_joins, :uniq => true
end

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.