Ruby-on-rails Rails has_one 带有类名和外键
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10664677/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Rails has_one with class name and foreign key
提问by pmerino
I have a Rails model which I use two has_onerelations: requesterand friend. When in the console I use:
我有一个 Rails 模型,我使用两个has_one关系:requester和friend. 在控制台中时,我使用:
f = FriendRequest.all
f[0].requester
I get ActiveRecord::StatementInvalid: SQLite3::SQLException: no such column: users.requester_id: SELECT "users".* FROM "users" WHERE "users"."requester_id" = 4 LIMIT 1.
我明白了ActiveRecord::StatementInvalid: SQLite3::SQLException: no such column: users.requester_id: SELECT "users".* FROM "users" WHERE "users"."requester_id" = 4 LIMIT 1。
I don't really know how to specify a `has_one' relationship with a class name and a key which specifies the record. This is my model:
我真的不知道如何用类名和指定记录的键来指定“has_one”关系。这是我的模型:
class FriendRequest < ActiveRecord::Base
has_one :requester, :class_name => "User", :foreign_key => "requester_id"
has_one :friend, :class_name => "User", :foreign_key => "friend_id"
end
How could I do it? In a belongs_torelationship I use the same, obviously replacing has_onewith belongs_to. Thanks!
我怎么能做到?在一段belongs_to关系中,我使用相同的,显然替换has_one为belongs_to. 谢谢!
回答by Baldrick
has_one :requester, :class_name => "User", :foreign_key => "requester_id"
This line (from the code that you posted) indicates that the requesteris a User, and the table usersshould contain a column requester_idthat is the foreign key toward friend_requestsrecords. The rails error message states that the column requester_iddoes not exists (you have to create it via a migration).
这一行(来自您发布的代码)表明requesteris a User,并且该表users应包含一列requester_id作为friend_requests记录的外键。rails 错误消息指出该列requester_id不存在(您必须通过迁移创建它)。
In this case, use
在这种情况下,使用
rails generate migration AddRequesterIdToUsers requester_id:integer
It will generate the migration:
它将生成迁移:
class AddRequesterIdToUsers < ActiveRecord::Migration
def change
add_column :users, :requester_id, :integer
end
end
And run them migration with rake db:migrate.
并使用rake db:migrate.
Look at the Rails Relation Guidefor more information on differences between has_oneand belongs_to, and how to use them.
查看Rails Relation Guide以获取有关has_one和之间差异belongs_to以及如何使用它们的更多信息。

