Elliot
Elliot

Reputation: 13845

Using before_create in rails3

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?

Upvotes: 0

Views: 766

Answers (3)

Vizjerai
Vizjerai

Reputation: 1972

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

Upvotes: 0

dombesz
dombesz

Reputation: 7909

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

Upvotes: 2

tbaums
tbaums

Reputation: 592

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).

Upvotes: 1

Related Questions