简体   繁体   中英

update record if exist else create new record rails

This is my 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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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