我使用迁移向Rails中的表添加了一个名为“version”的新列,并将相应的参数手动添加到相应控制器中允许的强参数中:
def endpoint_params
params.require(:endpoint).permit(:hostname, :username, :password, :connection_string, :entity_id, :created_at,
:updated_at, :endpoint_type_id, :endpoint_app_id, :environment_id, :created_by,
:updated_by, :version)
end
但是,当我尝试在更新操作中设置该新参数并将其保存到数据库时,它根本不会被保存。我正在使用的代码是:
def update
begin
@environment = Environment.find(params[:env])
version_no = (EndpointsFile.where("environment_id = ?", @environment.id).maximum('version') || 0) + 1
@endpoint.updated_by = current_user.id
@endpoint.version = version_no
respond_to do |format|
if @endpoint.update(endpoint_params)
@endpoints = Endpoint.where("environment_id = ? and id <> ?", @environment.id, @endpoint.id)
EndpointsFile.create!(version: version_no, date: Time.now, environment_id: @environment.id)
@endpoints.each do |e|
e.version = version_no
e.save
puts "e.version: #{e.version}" **=> HERE IT PRINTS e.version: and the field is null in the database**
end
format.html { redirect_to env_endpoints_path(env: @environment.id), notice: t('.notice') }
format.json { render :show, status: :ok, location: @endpoint }
else
format.html { render :edit }
format.json { render json: @endpoint.errors, status: :unprocessable_entity }
end
end
rescue => exception
logger.error { "endpoints_controller.update -> Ocorreu um erro ao atualizar o endpoint: #{exception.message}" }
respond_to do |format|
format.html { redirect_to env_endpoints_path(env: @environment.id), alert: "Ocorreu um erro ao atualizar o endpoint: #{exception.message}" and return }
format.json { render json: @endpoint.errors, status: :unprocessable_entity }
end
end
end
这是端点模型:
class Endpoint < ApplicationRecord
belongs_to :entity
belongs_to :environment
belongs_to :endpoint_app
belongs_to :endpoint_type
has_many :configs_histories
has_paper_trail
end
DB中的表格是:
create_table "endpoints", force: :cascade do |t|
t.string "hostname"
t.string "username"
t.string "password"
t.string "connection_string"
t.integer "entity_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "endpoint_type_id"
t.integer "endpoint_app_id"
t.integer "environment_id"
t.integer "created_by"
t.integer "updated_by"
t.integer "version"
t.index ["endpoint_app_id"], name: "index_endpoints_on_endpoint_app_id"
t.index ["endpoint_type_id"], name: "index_endpoints_on_endpoint_type_id"
t.index ["entity_id"], name: "index_endpoints_on_entity_id"
t.index ["environment_id"], name: "index_endpoints_on_environment_id"
end
我做错了什么?为什么命令e.save
不起作用?
答案 0 :(得分:1)
答案 1 :(得分:0)
由于您在version_no
内计算update
,因此您不必在控制器中传递它或在强参数中允许,只需执行以下操作
@endpoint.update(endpoint_params.merge(version: version_no))