Sunday, 15 February 2015

Rails and database: find entry if exists else create -



Rails and database: find entry if exists else create -

i have table in database has next columns:

id package1_name package2_name

and have 2 file_fields in _form.html.erb:

<%= form_for(@submission, :html => { :multipart => true }) |f| %> <%= f.fields_for :uploads |upload| %> <%= upload.file_field :package1 %> <%= upload.file_field :package2 %> <% end %> <% end %>

every time click submit button create 2 separate entries in database.

is there way alter behavior of create find database entry if exist else create new entry?

i have tried doesnt work:

def create @submission = submission.find_or_create_by_id(params[:submission]) ... end

this create submission if record id in params[:submission][:id] doesn't exist.

def create @submission = submission.where(:id => params[:submission][:id]).first_or_create(params[:submission]) end

however, abhir doesn't seem right form calls create method twice. seems weird need this. anyway, in case behavior correct, hope help.

ruby-on-rails

No comments:

Post a Comment