In my rails app, i have a submission form.
I am using a legacy database where the sub开发者_JAVA百科mission id value is retrieved from a sequence table This sequence value is used as the primary key for my submission
So in my form, i want to pass the sequence value as primary but it's not working
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
I noticed that the following line does not work:
<%= f.hidden_field :SUB_OID, :value => $temporary_id %>
However, to pass the sequence value as submission id, i have to put the following line in the def create function:
@submission.SUB_OID= $temporary_id
The thing now is i want to know if i can pass the primary id of the submission in the new.html.erb page itself, instaed of declaring it in the def create function.
Many thanks for looking into this..
cheers
Better to leave the ID out of your forms and set it on 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
精彩评论