Rails:一对多关联

发布于 2024-11-09 11:25:41 字数 735 浏览 0 评论 0原文

我正在使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

半衬遮猫 2024-11-16 11:25:41

我相信您还需要在用户模型中的 has_many 关联声明中指定 :foreign_key 选项。

class User
  has_many :subject_families, :foreign_key => 'assigned_to'

I believe you also need to specify the :foreign_key option on the has_many association declaration in your User model.

class User
  has_many :subject_families, :foreign_key => 'assigned_to'
柠檬色的秋千 2024-11-16 11:25:41

您需要指定 :foreign_key => User 上的 has_many 关系中的“signed_to” 也是如此。

You need to specify :foreign_key => 'assigned_to' in the has_many relationship on User as well.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文