1

谷歌搜索为此,我看到Rails核心团队正在为Rails 4开发一个解决方案,但这是一种解决方法。无法创建记录,因为连接表需要created_at(HABTM + Rails)

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在这里是错误的吗?

+0

为了您的信息:has_and_belongs_to_many也被称为“多对多”的关系。 – Kamil

回答

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

+0

构建给了我一个新的错误,'未定义的方法stringify_keys'。我也认为这会有助于以某种方式编写迁移以使'created_at'和'updated_at'字段为'null => true' –

+0

我更新我的答案请尝试 –

+0

@ circle.location是什么? –

-1

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

0

就试试这个

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

可能无法正常工作,我还没有尝试过在当地,SRY生根粉那^ _^

1

我最终得到它通过从时间戳工作用于创建连接表的迁移。

正确的模式应该是这样的:

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