views:

29

answers:

1

I have a type I want to save to the database, say, email addresses, and I want to save them in the most efficient way possible. I also want to associate posts with email addresses, so if it exists, I want to assign the post to that email address. Should I do a search first and then go based on that result, or is there a more efficient way? for ex, if it doesn't exist, I just want it to insert, I don't want to then to have to insert it after a search; that takes 2 calls where 1 would do.

+3  A: 

I believe you should use something like find_or_create.

Does post and email are separated models and post has_one email?

Edit

When creating a post, you should do something like

# posts controller
@email = Email.find_or_initialize_by_address(params[:email])
@post.email = @email #or whatever you do to associate them
j.
well, there are many types of posts, and email has a polymorphic relationship to them through an intermediate table is_postable.
tesmar
I've edited my answer :] The important part is the `find_or_initialize_by`.
j.