SQLite3 :: ConstraintException:约束失败:

时间:2013-02-05 15:05:05

标签: ruby-on-rails database ruby-on-rails-3 rails-activerecord

我正在尝试学习Ruby on Rails并遇到了我需要帮助的问题。我要做的是创建一个带有表单的“项目经理”,但是当我填写表单并点击提交时会显示以下错误:

ActiveRecord::StatementInvalid in ProjectsController#create

SQLite3::ConstraintException: constraint failed: INSERT INTO "projects" ("created_at", "description", "end_date", "start_date", "title", "updated_at", "user_id") VALUES (?, ?, ?, ?, ?, ?, ?)

Rails.root: /Applications/XAMPP/xamppfiles/htdocs/IDV450-labb1

Application Trace | Framework Trace | Full Trace
app/controllers/projects_controller.rb:14:in `create'

项目控制人:

1.   class ProjectsController < ApplicationController
2.
3.      def index
4.        @projects = Project.all
5.      end
6.
7.      def new
8.        @project = Project.new
9.      end
10.
11.     def create
12.       @project = Project.new(params[:project].merge(:user_id => current_user.id))
13.
14.       if @project.save
15.         redirect_to projects_path
16.       else
17.         render :action => "new"
18.       end
19.     end
20.   end

项目模型:

class Project < ActiveRecord::Base
    has_and_belongs_to_many :users
    belongs_to :ticket

    attr_accessible :user_id, :title, :description, :start_date, :end_date
end

新项目的观点:

<%= form_for @project do |f| %>
    <div class="text_field">
        <%= f.label :title%>
        <%= f.text_field :title%>
    </div>
    <div class="text_field">
        <%= f.label :description%>
        <%= f.text_field :description%>
    </div>
    <div class="dropdown">
        <%= f.label :start_date%>
        <%= date_select :start_date, :startdate %>
    </div>
    <div class="dropdown">
        <%= f.label :end_date%>
        <%= date_select :end_date, :enddate %>
    </div>
    <div class="select">
        <%= f.label :title%>
    </div>
    <div class="submit">
        <%= f.submit "Save" %>
    </div>
<% end %>

数据库模型:

Project:
    - id: int
    - user_id: int
    - title: varchar(50)
    - description: varchar(500)
    - start_date: date
    - end_date: date
    - created_at: datetime
    - updated_at: datetime

请求发送的参数:

{"utf8"=>"✓",
 "authenticity_token"=>"CrFUjpsRCEWRprSmKtOk4nBxsxrwaII1WKLDWMQWuUI=",
 "project"=>{"title"=>"Foo project",
 "description"=>"A little description"},
 "start_date"=>{"start_date(1i)"=>"2013",
 "start_date(2i)"=>"2",
 "start_date(3i)"=>"7"},
 "end_date"=>{"end_date(1i)"=>"2014",
 "end_date(2i)"=>"3",
 "end_date(3i)"=>"12"},
 "commit"=>"Spara"}

它确实没有说明问题是什么,但它在第14行尝试保存到数据库时发生。如果我在种子中创建一个项目就可以了!

2 个答案:

答案 0 :(得分:5)

也许您对项目模型或项目表(可在schema.rb文件中看到)进行了一些验证失败

或者您可以尝试通过从模型中删除所有属性并尝试创建对象来逐步检查创建项目模型

尝试打印@project对象并查看其用于创建的值

你应该使用保存!而不是保存

希望有所帮助......

:)

答案 1 :(得分:4)

你桌上有什么索引?您要么违反非空约束(缺少数据),要么违反唯一性约束(插入记录中的重复数据)。