Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do I reject if exists? for non-nested attributes?
    primarykey
    data
    text
    <p>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:</p> <blockquote> <p>@links = params[:links].values.collect{ |link| current_user.links.create(link) }.reject { |p| p.errors.empty? }</p> </blockquote> <p>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.)</p> <p>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?</p> <p>Edit: Thanks to Kandada, I'm now using this:</p> <blockquote> <p>@links = params[:links].values.collect.reject{ |link| current_user.links.exists?(:url=>link[:url])}</p> <p>@links = @links.collect{ |link| current_user.links.create(link) }.reject { |p| p.errors.empty? }</p> </blockquote> <p>So I separated the two, to first check if there are any that exist, then to create those that weren't rejected. Is there a better way to do this, like maybe combining the two statements would increase performance? If not, I think I'm pretty satisfied. (thank you again Kandada and j.)</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload