1
votes

In my model I have

    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

end

In my controller:

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

And in my view

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

For me it looks preatty normal, but when I'm trying to save new alias, it results with with:

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:name@localhost: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'

What could be the problem? I'm using rails3, postgres and datamapper.

3

3 Answers

0
votes

Not familiar with rails internals, but your column's definition must be so that it allow null values.

2
votes

It appears you have fields in your database that aren't defined in your model, and that some of those fields have not-null constraints on them. Because datamapper only writes the fields it knows about (in this case :id), it does not specify values for any additional fields that might exist in the table. Since the unspecified fields require values, PgSQL is producing an error.

Either remove the not-null constraints, or add those fields to DataMapper with :default values on them.

0
votes

I had the same problem with data mapper. This is what I did to fix it:

In Alias class, add an additional line as follows:

property :user_id, Integer

This line defines the foreign key.