【问题标题】:Unable to create a record because join table requires created_at (HABTM + Rails)无法创建记录,因为连接表需要 created_at (HABTM + Rails)
【发布时间】:2012-10-26 06:32:39
【问题描述】:

在谷歌上搜索,我看到 Rails 核心团队正在为 Rails 4 开发解决方案,但那还有很长的路要走。

UsersCircles 都具有has_and_belongs_to_many 关系。

我的架构如下所示:

  create_table "circles", :force => true do |t|
    t.string   "name"
    t.datetime "created_at", :null => false
    t.datetime "updated_at", :null => false
  end

  create_table "circles_users", :force => true do |t|
    t.integer  "circle_id"
    t.integer  "user_id"
    t.datetime "created_at", :null => false
    t.datetime "updated_at", :null => false
  end

  create_table "users", :force => true do |t|
    t.string   "name"
    t.string   "email"
    t.datetime "created_at", :null => false
    t.datetime "updated_at", :null => false
    t.string   "password"
  end

但在我的代码中,在我的circles_controller 中,当我尝试这样做时:

  def create
    @circle = Circle.new(params[:circle])
    @circle.users << User.find(session[:user].id)
...

我的浏览器出现以下错误:

SQLite3::ConstraintException: circles_users.created_at may not be NULL: INSERT INTO "circles_users" ("circle_id", "user_id") VALUES (11, 5)

created_atupdated_at 在这里是假的,我该怎么办?

【问题讨论】:

  • 供您参考:has_and_belongs_to_many 也称为“多对多”关系。

标签: ruby-on-rails sqlite migration schema has-and-belongs-to-many


【解决方案1】:

我最终通过从用于创建连接表的迁移中删除时间戳来使其工作。

正确的架构应该是这样的:

create_table "circles_users", :force => true do |t|
t.integer  "circle_id"
t.integer  "user_id"
  end

【讨论】:

    【解决方案2】:

    试试这个

    def new
     @circle = Circle.new
     1.times { @circle.users.build } if @circle.users.nil?
    end
    
    def create
      @circle = Circle.new(params[:circle])
      @circle.update_attributes(session[:user]) # this will automatically update location table by using relationship
      @circle.save   
    end
    

    HABTM

    【讨论】:

    • Build 给了我一个新错误,undefined method stringify_keys。我还认为以某种方式编写迁移以使 created_atupdated_at 字段成为 null =&gt; true 会有所帮助
    【解决方案3】:

    试试这个

    def create
      @circle = Circle.new(params[:circle])
      @circle.users = [User.find(session[:user].id)]
    

    可能不行,我本地没试过,不好意思^_^

    【讨论】:

      【解决方案4】:

      在这些日期时间字段中,您应该插入当前时间戳或将它们更改为可空字段(如果您不使用数据填充它们)。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-04-25
        • 2011-01-23
        • 1970-01-01
        • 1970-01-01
        • 2013-08-07
        • 1970-01-01
        相关资源
        最近更新 更多