Using before_create in rails3

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

Currently, when a new tag is created, a connection is created, a connection to the tag, and the publication of the tag. The problem is that 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 was already created, I would like the connection to use the original tag identifier, rather than letting it create a new tag identifier.

Any tips on how I can do this?

0
source share
3 answers

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

Update

, , :

@post.tags.find_or_create_by_name('tag_name')

,

@post.tags.find_or_initialize_by_name('tag_name')

name "tag_name".

, , , , . a >

2

has_many: , : ` find_or_create_by` `has_many`` via`

+2

:before_save?

:

:before_save :method_to_check_something

... , ( , ).

+1

This should take care of duplicate entries between the Mail and the tag, but don’t know how your user associations are configured.

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

All Articles