简体   繁体   English

如果不存在,则使用#update方法创建新记录

[英]Using #update method to create new record if one does not exist

In Admin::SettingsController , I want to create a new Survey record if one does not exists, OR updates existing Survey record. Admin::SettingsController ,我想创建一个新的Survey记录(如果不存在),或者更新现有的Survey记录。 What is the best Rails way to handle the creation and lookup? 处理创建和查找的最佳Rails方法是什么? My error back is No route matches [POST] "/admin/settings" 我的错误是No route matches [POST] "/admin/settings"

edit_admin_settings_path    GET     /admin/settings/edit(.:format)  admin/settings#edit
admin_settings_path         PATCH   /admin/settings(.:format)   admin/settings#update
                            PUT     /admin/settings(.:format)   admin/settings#update

routes 路线

resource  :settings,            only: [:edit, :update]

controller 调节器

class Admin::SettingsController < Admin::BaseController
  before_action :load_survey

  def edit
    @survey = Survey.find_or_initialize_by(id: params[:id]) unless @survey
  end

  def update
    @survey.update_attributes!(params_for_create_or_update)
    flash[:notice] = 'Survey updated'
    redirect_to action: :edit
  end

protected

  def load_survey
    @survey = Survey.last || Survey.new
  end

  def params_for_create_or_update
    params.require(:survey).permit(
      :name,
      :link,
      :language_id
    )
  end
end

Take a look at find_or_create_by method: 看一下find_or_create_by方法:

  def update
    @survey = Survey.find_or_create_by(id: params[:id])
    @survey.update_attributes!(params_for_create_or_update)
    flash[:notice] = 'Survey updated'
    redirect_to action: :edit
  end

This will try to find a record with that particular id and create one if it doesn't exist. 这将尝试查找具有该特定id的记录,如果不存在则创建一个。 Then you can simply update the record as you see fit. 然后,您可以根据需要更新记录。

Edit 编辑

you can also use find_or_initialize_by which calls new to instantiate the object instead of create 你也可以使用find_or_initialize_by调用new来实例化对象而不是create

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

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