Rails belongs_to不会使用自定义类名设置外键ID

Hei*_* Yu 8 belongs-to ruby-on-rails-3

我的模型设置如下:

class User < ActiveRecord::Base
  has_many :posts, :foreign_key => 'author_id'
end

class Post < ActiveRecord::Base
  belongs_to :author, :class_name => 'User'
end
Run Code Online (Sandbox Code Playgroud)

假设:

p = Post.first # just any post instance
a = User.first # any user instance
Run Code Online (Sandbox Code Playgroud)

现在这段代码表现得非常奇怪

p.author = a
Run Code Online (Sandbox Code Playgroud)

设置作者后,author_id帖子的属性应设置为用户的id.但这不会发生.

我尝试使用belongs_to没有class_name参数的模型,一切都按预期工作.

现在,还有一件令人讨厌的事情是,当我改变关联时belongs_to :author, :class_name => 'User', :foreign_key => 'author_id',它会令人惊讶地起作用.

这是Rails 3.0.9中的错误吗?外键参数不应该是不必要的,因为正如文档所说,它的默认值是附加的关联的名称_id.

另请注意,即使没有:foreign_key => 'author_id',关联关系的其他所有内容都按预期工作.(就像获取相关模型一样)唯一不起作用的是setter方法没有设置外键.

我知道我可以做p.author_id = a.id或者只是将:foreign_keyparams 添加到我的所有关联中class_name,但我更喜欢更优雅的语法p.author = a

Hei*_* Yu 6

阅读了很多Rails代码并在此处跟踪我发现的内容:

这个bug存在是因为gem composite_primary_keys覆盖了默认的rails reflection.rb.

我将不得不检查他们如何实现primary_key_namederive_primary_key_name方法.

这个愚蠢的小虫浪费了相当多的时间,但至少我学到了很多关于ActiveRecord内部的知识.