开发者

Rails efficient way to save non-duplicates?

开发者 https://www.devze.com 2023-01-04 10:53 出处:网络
I ha开发者_JAVA技巧ve 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 i

I ha开发者_JAVA技巧ve 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.


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
0

精彩评论

暂无评论...
验证码 换一张
取 消