2011-06-16 102 views
1

在我的模型我有“数据对象:: IntegrityError(错误:在列空值违反非空约束” 在轨误差3

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 %> 

对我来说,它看起来preatty正常,但是当我试图保存新的别名,它导致用:

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

Processing by AliasesController#create as HTML Parameters: {"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_attempts", "unlock_token", "locked_at", "sign_in_count", "current_sign_in_at", "last_sign_in_at", "current_sign_in_ip", "last_sign_in_ip", "username", "email", "name", "country" FROM "users" WHERE "id" IN (2) LIMIT 1 ~
SQL (0.491ms) SELECT "id" FROM "aliases" WHERE "id" = 'IDNAME' ORDER BY "id" LIMIT 1 Completed in 11ms ~ SQL (0.531ms) INSERT INTO "aliases" ("id", "user_id") VALUES ('IDNAME', 2) ~ ERROR: null value in column "alias_id" violates not-null constraint (code: 33575106, sql state: 23502, query: INSERT INTO "aliases" ("id", "user_id") VALUES ('IDNAME', 2), uri: postgres:[email protected]:5432postgres?adapter=postgres&host=localhost&port=5432&username=name&password=pass&database=postgres&path=postgres&schema_search_path=public&encoding=utf8&template=template0)

DataObjects::IntegrityError (ERROR: null value in column "alias_id" violates not-null constraint):
app/controllers/aliases_controller.rb:5:in `create'

可能是什么问题呢?我正在使用rails3,postgres和datamapper。

回答

0

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

2

看起来您的数据库中有未定义在您的模型中的字段,并且其中一些字段对它们有非空限制。由于datamapper只写入它所了解的字段(在本例中为:id),因此它不会为该表中可能存在的任何其他字段指定值。由于未指定的字段需要值,因此PgSQL会产生错误。

要么删除非空约束,要么将这些字段添加到DataMapper中,其值为:default

0

我有与数据映射器相同的问题。 这是我做过什么来解决这个问题:

别名类,如下所示添加一个附加行:

property :user_id, Integer 

这一行定义外键。

相关问题