如果存在用新数据覆盖,则在rails中创建新行

时间:2016-06-06 12:07:34

标签: ruby-on-rails ruby ruby-on-rails-4 ruby-on-rails-4.2 ruby-2.0

我正在使用Ruby 2和Rails 4.我想创建新数据,如果' name'不存在,如果存在,则使用新数据进行更新。从我的照片来看,如果&#l; lol'存在,在上传时更新新的pdf文件,否则用新数据创建新行。我怎样才能做到这一点?如果有任何想法,请与我分享。

enter image description here

我的代码是: Static_pages控制器:

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>

3 个答案:

答案 0 :(得分:2)

我知道这看起来有点难看,但应该可以解决这个问题

def create_form
  contact = Contact.find_or_initialize_by(name: params[:contact][:name])
  contact.file = params[:contact][:file]

  if contact.save
    redirect_to :back
  else
    redirect_to downloads_form_path
  end
end

答案 1 :(得分:1)

您可以使用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

答案 2 :(得分:0)

得到了解决方案

@form_downup = Contact.find_or_create_by(:name => contact_params[:name])   
@form_downup.file=contact_params[:file]
@form_downup.save