ruby on rails遗留数据库 - 从另一个表中检索的主要ID

时间:2011-05-16 14:52:43

标签: ruby-on-rails

在我的rails应用程序中,我有一个提交表单。

我正在使用遗留数据库,其中从序列表中检索提交ID值此序列值用作我提交的主键

所以在我的表单中,我想将序列值作为主要值传递,但它不起作用

new.html.erb:

<% form_for @submission, :html => { :multipart => true } do |f| %>

<%= f.hidden_field :SUB_OID, :value => $temporary_id %>

<% end %>

submission.rb:

class SubmissionsController < ApplicationController
#retrieve id for new submission
result = ActiveRecord::Base.connection.execute('SELECT SEQ_TEMP_ID FROM ref_sequences')
inc_result = (result.fetch_row.first)


#increment temporary id by 1
$temporary_id = (inc_result.to_i) + 1

def create
@submission = Submission.new(params[:submission])
###@submission.SUB_OID= $temporary_id ###

  if @submission.save

  #after temp submission is saved, update id in ref_sequences table#
  ActiveRecord::Base.connection.execute("UPDATE ref_sequences SET SEQ_TEMP_ID = SEQ_TEMP_ID + 1")

  flash[:notice] = 'Submission was successfully created'
      redirect_to show_submission_path(@submission.SUB_OID)

  else
  render :action => 'new'
  end

end

end

我注意到以下行不起作用:

<%= f.hidden_field :SUB_OID, :value => $temporary_id %>

但是,要将序列值作为提交ID传递,我必须在def create函数中放入以下行:

@submission.SUB_OID= $temporary_id

现在我想知道我是否可以在new.html.erb页面中传递提交的主要ID,并在def create函数中声明它。

非常感谢您对此进行调查..

欢呼声

1 个答案:

答案 0 :(得分:1)

最好将ID从表单中删除并将其设置为save:

class Submission < ActiveRecord::Base

  before_create :fetch_id
  after_create  :update_sequence_table

private

  def fetch_id
    self[:id] = connection.execute('SELECT SEQ_TEMP_ID FROM ref_sequences')
  end

  def update_sequence_table
    connection.execute("UPDATE ref_sequences SET SEQ_TEMP_ID = SEQ_TEMP_ID + 1")
  end

end