Priyank Dey Priyank Dey - 5 months ago 11
Ruby Question

if exists overwrite with new data else create new row in rails

I am using Ruby 2 and Rails 4. I want to create new data if the 'name' does not exist, and if it exists then update with new data. From my picture, if 'lol' exists, update new pdf file when uploading else create new row with new data. How can I do this? Please share with me if any has any idea.

enter image description here

My codes are:
Static_pages controller:

def create_form
@form_downup = Contact.new(contact_params)
if @form_downup.save

redirect_to :back
else
redirect_to downloads_form_path
end
end

private
def contact_params
params.require(:contact).permit(:name,:file)

end


downloads_form.html.erb

<table class="table table-condensed table-responsive">
<tbody>
<%= form_tag create_form_path, multipart: true do |f| %>
<tr>
<td class=""><%= text_field_tag "contact[name]", nil, class: "form-control" %></td>
<td><%= file_field_tag "contact[file]", class: "form-control" %></td>
<td><%= submit_tag 'Upload' %></td>
<td><%= link_to "Download", static_pages_downloadform_pdf_path(:file_name => "lol") %></td>

</tr>

<% end %>

</tbody>
</table>

Answer

You can use find_or_initialize_by.

def create_form
    @form_downup = Contact.find_or_initialize_by(name: params[:contact][:name])
    @form_downup.file = params[:contact][:file]
    if @form_downup.save
      redirect_to :back
    else
      redirect_to downloads_form_path
    end
end
Comments