导轨 3 中的"DataObjects::IntegrityError (ERROR: null value in column violates not-null constraint"错误



在我的模型中,我有

    class Alias
  include DataMapper::Resource

  belongs_to :user

  property :id, String, :key => true, :required => true, :unique => true
  validates_format_of :id, :with => /[0-9a-z-]/i

结束

在我的控制器中:

def new
   @new_alias = @owner.aliases.new()
end
    def create 
         @owner = current_user
         @alias = @owner.aliases.create(params[:alias])
end

在我看来

<%= form_for @new_alias, :url => {:controller => "aliases", :action=>"create"} do |f| %> 
    <%= f.text_field :id, :placeholder => "Account name" %></br>
    <%= f.submit :value => "Create" %>
 <% end %>

对我来说,这看起来很正常,但当我试图保存新的别名时,结果是:

ERROR:  null value in column "alias_id" violates not-null constraint

AliasesController处理#create作为HTML参数:{"utf8"=>"✓","authenticity_token"=>"/token=","alias"=>{"id"=>"IDNAME"},"commit"=>"Create"}~SQL(0.632ms)SELECT"id","encrypted_password","remember_created_at","reset_password_token","reset_password_sent_at","failed_tempts"、"unlock_token","locked_at","sign_in_count","current_sign_in_at","lastrongign_in_at","current_sign_in_ip","lastrongign_in_ip","用户名","电子邮件"、"姓名"、"国家/地区"FROM"users"WHERE"id"IN(2)LIMIT 1~
SQL(0.491ms)从中选择"id"别名"WHERE"id"='IDNAME'ORDERBY"id"LIMIT 1在11毫秒内完成~SQL(0.531ms)INSERT INTO"别名"("id","user_id")值("DNAME",2)~错误:列中为null值"alias_id"违反非null约束(代码:33575106,sql状态:23502,查询:INSERT INTO"别名"("id"、"user_id")值("DNAME",2),uri:进展后:name@localhost:5432 Postgres?adapter=postgres&host=localhost&端口=5432&username=name&password=pass&database=postgres&path=postgres&schema_sasearch_path=公共&编码=utf8&template=template0)

DataObjects::IntegrityError(错误:列"alias_id"中的null值违反非null约束):
app/controllers/aliases_controller.rb:5:in`创建

可能是什么问题?我使用rails3、postgres和datamapper。

您的数据库中似乎有未在模型中定义的字段,并且其中一些字段没有null约束。因为datamapper只写入它知道的字段(在本例中为:id),所以它不会为表中可能存在的任何其他字段指定值。由于未指定的字段需要值,PgSQL产生了一个错误。

移除非null约束,或者将这些字段添加到DataMapper中,并在其上添加:default值。

不熟悉rails内部,但列的定义必须允许空值。

我在数据映射器方面也遇到了同样的问题。这就是我修复它的方法:

Alias类中,添加一行,如下所示:

property :user_id, Integer

此行定义外键。

最新更新