1

对此进行谷歌搜索,我看到 Rails 核心团队正在研究 Rails 4 的解决方案,但那还有很长的路要走。

两者Users都有Circles关系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

4

4 回答 4

1

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

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

create_table "circles_users", :force => true do |t|
t.integer  "circle_id"
t.integer  "user_id"
  end
于 2013-08-07T02:14:54.297 回答
0

尝试这个

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

于 2012-10-26T07:03:40.897 回答
0

试试这个

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

可能不行,我没有在本地尝试过,sry abt ^_^

于 2012-10-27T04:21:18.447 回答
-1

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

于 2012-10-27T04:11:23.300 回答