我无法创建记录或检查记录是否存在。我正在向“Checks”控制器提交两个条目来创建“id”和“uid”。下面的迁移:
create_checks
class CreateChecks < ActiveRecord::Migration[5.0]
def change
create_table :checks do |t|
t.timestamps
end
end
end
add_uid_to_checks
class AddUidToChecks < ActiveRecord::Migration[5.0]
def change
add_column :checks, :uid, :string
end
end
Checks_controller#创建
def create
@check = Check.new(check_params)
respond_to do |format|
if @check.save
format.html { redirect_to @check, notice: 'Check was successfully created.' }
format.json { render :show, status: :created, location: @check }
else
format.html { render :new }
format.json { render json: @check.errors, status: :unprocessable_entity }
end
end
end
通过ajax提交了两个参数 - ID和UID
,它给了我以下内容Started POST "/checks.json" for ::1 at 2016-09-05 09:36:31 -0500
Processing by ChecksController#create as JSON
Parameters: {"id"=>"54545454", "uid"=>"23232323"}
(0.0ms) begin transaction
SQL (2.0ms) INSERT INTO "checks" ("created_at", "updated_at") VALUES (?, ?)
[["created_at", 2016-09-05 14:36:31 UTC], ["updated_at", 2016-09-05 14:36:31 UTC
]]
(10.0ms) commit transaction
Rendering checks/show.json.jbuilder
Rendered checks/_check.json.jbuilder (1.0ms)
Rendered checks/show.json.jbuilder (9.0ms)
Completed 201 Created in 201ms (Views: 174.8ms | ActiveRecord: 12.0ms)
然后我检查它是否存在使用此控制器......
def set_check
if Check.exists?(params[:id])
render plain: "1"
else
render plain: "0"
end
end
这给了我......
Started GET "/checks/54545454" for ::1 at 2016-09-05 0
9:36:37 -0500
Processing by ChecksController#show as */*
Parameters: {"id"=>"54545454"}
Check Exists (1.0ms) SELECT 1 AS one FROM "checks" WHERE "checks"."id" = ? L
IMIT ? [["id", 0], ["LIMIT", 1]]
Rendering text template
Rendered text template (0.0ms)
Filter chain halted as :set_check rendered or redirected
Completed 200 OK in 7ms (Views: 1.8ms | ActiveRecord: 1.0ms)
并且找不到“0”。我确定我做错了什么,但我无法确定在哪里。
更多代码位:
Routes.rb相关部分:
resources :checks
定义了set_checks(在控制器的顶部,在ChecksController&lt; ApplicationController类的正下方)
before_action :set_check, only: [:show, :edit, :update, :destroy]
答案 0 :(得分:1)
ActiveRecord使用id
列作为主键 - 它是一个自动递增列,因此在将记录插入表时设置该值。因此,在创建新记录时,您永远不会将ID作为参数传递。
事实上,如果你检查新创建的记录的id,它与参数:
不同def create
@check = Check.new(check_params)
logger.info("id param is: #{ params[:id] }")
respond_to do |format|
if @check.save
logger.info("Check id is: #{ @check.id }")
format.html { redirect_to @check, notice: 'Check was successfully created.' }
format.json { render :show, status: :created, location: @check }
else
format.html { render :new }
format.json { render json: @check.errors, status: :unprocessable_entity }
end
end
end
已添加 - 如果您不打算使用主键,则不应使用id
作为列名。