簡體   English   中英

更新記錄(如果存在),否則創建新記錄

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

這是我的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 %>

這是我的控制器

  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

上面的代碼每次都在創建新記錄

gen_id是Post表單的一部分。 但是您正在尋找頂級產品。 您需要這樣做:

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

要么

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM