Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/solr/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 如果数据库中没有外键,rails关联是否应该抛出错误?_Ruby On Rails_Associations_Belongs To - Fatal编程技术网

Ruby on rails 如果数据库中没有外键,rails关联是否应该抛出错误?

Ruby on rails 如果数据库中没有外键,rails关联是否应该抛出错误?,ruby-on-rails,associations,belongs-to,Ruby On Rails,Associations,Belongs To,在关联的情况下,rails似乎允许您设置关联,即使表中没有相应的外键。这是预期的行为吗 见以下情况: $> rails new mynewapp $> cd mynewapp $> rails g model User $> rails g model Whatever $> rake db:migrate #user.rb belongs_to :whatever $> rails c u = User.new u.save w = W

在关联的情况下,rails似乎允许您设置关联,即使表中没有相应的外键。这是预期的行为吗

见以下情况:

$> rails new mynewapp
$> cd mynewapp
$> rails g model User
$> rails g model Whatever
$> rake db:migrate

#user.rb
belongs_to :whatever

$> rails c
   u = User.new
   u.save
   w = Whatever.new
   w.save
   u.whatever = w
   u.save #no error!  

   u.whatever               #=> w(Whatever)
   u.reload                 #=> w(Whatever)
   User.find(u.id).whatever #=> nil!!!!!!

我在rails v3.2.3上看到了这种行为,这是预期的行为,因为关联并不总是涉及用户id类型列。如果您认为这会引发错误,那么这可能更适合rails github问题页面或rails开发邮件列表。

这一行为在任何地方都有记录吗?没有--我感觉列出所有不会引发错误的内容可能会是一个很长的文档。也许,但gotcha应该是这样的,也许我会提交一些东西;)