How do I reject if exists? for non-nested attributes?

Posted by GoodGets on Stack Overflow See other posts from Stack Overflow or by GoodGets
Published on 2010-04-01T18:50:48Z Indexed on 2010/04/01 18:53 UTC
Read the original article Hit count: 269

Filed under:

Currently my controller lets a user submit muliple "links" at a time. It collects them into an array, creates them for that user, but catches any errors for the User to go back and fix. How can I ignore the creation of any links that already exist for that user? I know that I can use validates_uniqueness_of with a scope for that user, but I'd rather just ignore their creation completely. Here's my controller:

@links = params[:links].values.collect{ |link| current_user.links.create(link) }.reject { |p| p.errors.empty? }

Each link has a url, so I thought about checking if that link.url already exists for that user, but wasn't really sure how, or where, to do that. Should I tack this onto my controller somehow? Or should it be a new method in the model, like as in a before_validation Callback? (Note: these "links" are not nested, but they do belong_to :user.)

So, I'd like to just be able to ignore the creation of these links if possible. Like if a user submits 5 links, but 2 of them already exist for him, then I'd just like for those 2 to be ignored, while the other 3 are created. How should I go about doing this?

© Stack Overflow or respective owner

Related posts about ruby-on-rails