.new没有为新对象分配id

时间:2015-01-31 01:30:25

标签: ruby-on-rails activerecord

我的ReportNu模型绑定到一个现有的表,其唯一的id列为" oid"。当我尝试创建新报告时,出现以下错误:

ERROR: null value in column "oid" violates not-null constraint DETAIL: Failing row contains (null, 2, 2, 106341051, 2016, 0, 0, null, null).

我觉得应该有一种方法告诉rails为我自动设置oid,从1开始递增。我怎么做?我加载了rails控制台,ReportNu.new只是创建一个oid为nil的实例。

以下是我文件的相关部分。

report_nu.rb:

class ReportNu < ActiveRecord::Base
  self.table_name = "t_report_cust"
  self.primary_key = "oid"
  ...
end

new.html.erb

<%= form_for(@report_nu) do |f| %>
  <%= f.hidden_field :cust_id, :value => current_user.id %><br>
  <div class="field">
    <%= f.label :spec_id %><br>
    <%= f.text_field :spec_id %>
  </div>
  <div class="field">
    <%= f.label :hid %><br>
    <%= f.text_field :hid %>
  </div>
  <div class="field">
    <%= f.label :fore_yr %><br>
    <%= f.text_field :fore_yr %>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

reports_controller.rb

  def new
    @report_nu = ReportNu.new
  end

  def create
    @report_nu = ReportNu.new(report_nu_params)

    respond_to do |format|
      if @report_nu.save
        format.html { redirect_to @report_nu, notice: 'Report nu was successfully created.' }
        format.json { render :show, status: :created, location: @report_nu }
      else
        format.html { render :new }
        format.json { render json: @report_nu.errors, status: :unprocessable_entity }
      end
    end
  end

1 个答案:

答案 0 :(得分:0)

@Pith在上面的评论中为我回答了这个问题。我正在使用的表没有将它的主键设置为自动递增。我没有创造这张桌子,甚至不知道要找那张桌子。谢谢Nithin!如果您将评论作为答案发布,我会检查并删除我自己的答案&#34;