Rails own_to 不使用自定义类名设置外键 id
我的模型设置如下:
class User < ActiveRecord::Base
has_many :posts, :foreign_key => 'author_id'
end
class Post < ActiveRecord::Base
belongs_to :author, :class_name => 'User'
end
假设:
p = Post.first # just any post instance
a = User.first # any user instance
现在这段代码的行为非常奇怪
p.author = a
设置作者后,帖子的属性 author_id
应设置为用户的 id。但这并没有发生。
我尝试使用具有 belongs_to
且没有 class_name
参数的模型,一切都按预期工作。
现在,另一件更奇怪的事情是,当我将关联更改为 belongs_to :author, :class_name => '用户', :foreign_key => 'author_id'
,它的效果令人惊讶。
这是 Rails 3.0.9 中的错误吗?外键参数不应该是不必要的,因为正如文档所说,它的默认值是附加 _id
的关联名称。
另请注意,即使没有 :foreign_key => 'author_id'
,有关关联的其他所有内容都按预期工作。 (就像获取关联模型一样)唯一不起作用的是 setter 方法没有设置外键。
我知道我可以只执行 p.author_id = a.id
或仅将 :foreign_key
参数添加到与 class_name
的所有关联中,但我更喜欢更优雅的语法 p.author = a
I have my models setup like so:
class User < ActiveRecord::Base
has_many :posts, :foreign_key => 'author_id'
end
class Post < ActiveRecord::Base
belongs_to :author, :class_name => 'User'
end
Assuming:
p = Post.first # just any post instance
a = User.first # any user instance
Now this piece of code is acting very weird
p.author = a
After setting the author, the attribute author_id
of the post should be set to the id of the user. But this isn't happening.
I tried using models with belongs_to
that does not have the class_name
parameter and everything works as expected.
Now, one more thing that makes it weirder is that when I change the association to belongs_to :author, :class_name => 'User', :foreign_key => 'author_id'
, it surprisingly works.
Is this a bug in Rails 3.0.9? Shouldn't the foreign key parameter be unnecessary because as the docs say, its default value is the name of the association appended with _id
.
Also note that even without :foreign_key => 'author_id'
, everything else regarding the association works as expected. (Like fetching the associated model) The only thing not working is the setter method not setting the foreign key.
I know I could just do p.author_id = a.id
or just add :foreign_key
params to all my associations with class_name
, but I prefer the more elegant syntax of p.author = a
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在阅读了大量 Rails 代码并跟踪后,我发现:
此错误的存在是因为 gem
composite_primary_keys
覆盖了默认的 Railsreflection.rb
。我必须检查他们如何实现
primary_key_name
和derive_primary_key_name
方法。在这个愚蠢的 bug 上浪费了相当多的时间,但至少我学到了很多关于 ActiveRecord 内部结构的知识。
After reading through lots of Rails code and tracing here's what I found:
This bug exists because of the gem
composite_primary_keys
which overrode the default railsreflection.rb
.I will have to check how they implemented the
primary_key_name
andderive_primary_key_name
methods.It was quite a bit of time wasted on this silly bug, but at least I got to learn a lot about ActiveRecord's internals.