简体   繁体   English

更新记录(如果存在),否则创建新记录

[英]update record if exist else create new record rails

This is my new.html.erb 这是我的new.html.erb

<%= form_for @post do |f| %>
    <%= f.text_field :title,placeholder: 'title' %>
    <%= f.hidden_field :gen_id,value: 55 %> #55 is just for testing
    <%= f.submit 'Submit' %>
<% end %>

This is my controller 这是我的控制器

  def create
      @post = Post.find_by_id params[:gen_id]
      if @post
        @post.update(post_params)
        else
          @post = Post.new
            if @post.save!
              flash[:success] = 'Post added successfully'
              redirect_to action: :new
            else
              flash[:error] = 'Post cannot add. Please try again after some time'
               redirect_to action: :new
            end
       end
   end

The above code is just creating new record everytime 上面的代码每次都在创建新记录

gen_id is part of Post form. gen_id是Post表单的一部分。 But you're looking for it at top level. 但是您正在寻找顶级产品。 You need to do this: 您需要这样做:

@post = Post.find_by_id params[:post][:gen_id]

or 要么

@post = Post.where(id: params[:post][:gen_id]).first

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM