刚学轨...为什么我无法将对象添加到关系中?
我有以下型号:
class TimeSlot < ActiveRecord::Base
has_and_belongs_to_many :users
end
class User < ActiveRecord::
has_and_belongs_to_many :time_slots
end
我也有一个模型,加入二:
class TimeSlotsUsers < ActiveRecord::Base
attr_accessible :time_slot_id, :user_id
end
在控制台中,我创建了一个用户对象,我想将它与TimeSlot关联起来。我有一个变量ts
,它是一个TimeSlot对象,而u
是一个用户对象。两者已经存在于数据库中。当我做ts.users << u
时,出现错误说“ActiveRecord :: StatementInvalid:SQLite3 :: ConstraintException:time_slots_users.created_at可能不是NULL:INSERT INTO”time_slots_users“(”time_slot_id“,”user_id“)VALUES(1,1)。
为什么会created_at在TimeSlotsUsers记录被创建时为空?是不是被自动创建的吗?我需要通过关系使用具有一对多的呢?
当使用'has_and_belongs_to_many'时,'updated_at'和'created_at'列不会被Rails设置。获得这种工作的唯一方法是通过黑客入侵Rails或向数据库添加触发器。你可能会删除它们,或者至少不要求它们。无法真正确定是否需要'has_many:through',但从连接模型看来,time_slots_users'实际上只是一个连接表,没有任何额外的属性。在这种情况下,一个简单的'has_and_belongs_to_many'就足够了,我的答案解决了这个问题。我同意你的其他意见。 – Mischa 2013-03-21 13:34:45
啊!我没有意识到'updated_at'和'created_at'没有设置。这就说得通了。就设计而言,现在该表是一个简单的连接表。 – 2013-03-21 15:41:28