Rails:一对多关联
我正在使用 Rails 3,并且我尝试定义一对多关联:一个用户可以分配给他/她许多主题系列,但一个主题系列只能分配给一个用户。
这是我定义的:
class User
has_many :subject_families
class SubjectFamily
belongs_to :assignee, :class_name => "User", :foreign_key => 'assigned_to'
我添加了一个执行此操作的迁移:
change_table(:subject_families) do |t|
t.integer :assigned_to
end
当我尝试执行以下操作时遇到异常:
u = User.first
s = u.subject_families
这是例外:
Invalid column name 'user_id'.: SELECT [subject_families].* FROM [subject_families] WHERE ([subject_families].user_id = 1)
我期望使用 subject_families.assigned_to 而不是 user_id 但你瞧,我很失望在这个期待中。谁能看到我在这里可能错过了什么?我已经用谷歌搜索了很多,从我看来这应该有效。
I'm using Rails 3 and I've got a one to many association I'm trying to define: A user can have many subject families assigned to him/her, but a subject family can only be assigned to one user.
Here's what I have defined:
class User
has_many :subject_families
class SubjectFamily
belongs_to :assignee, :class_name => "User", :foreign_key => 'assigned_to'
I added a migration that does this:
change_table(:subject_families) do |t|
t.integer :assigned_to
end
I'm getting an exception when I try to do:
u = User.first
s = u.subject_families
Here's the exception:
Invalid column name 'user_id'.: SELECT [subject_families].* FROM [subject_families] WHERE ([subject_families].user_id = 1)
I was expecting this to be using subject_families.assigned_to rather than user_id but lo and behold I was disappointed in this expectation. Can anyone see what I might have missed here? I've googled this a lot and from what I can see this SHOULD work.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我相信您还需要在用户模型中的 has_many 关联声明中指定 :foreign_key 选项。
I believe you also need to specify the :foreign_key option on the has_many association declaration in your User model.
您需要指定
:foreign_key =>
也是如此。User
上的has_many
关系中的“signed_to”You need to specify
:foreign_key => 'assigned_to'
in thehas_many
relationship onUser
as well.