与has_many:的Rails模型关联与NameError失败

时间:2012-01-23 16:55:05

标签: ruby-on-rails-3 activerecord naming-conventions

我想通过has_many:through关联两个模型(Team和Member),但返回NameError。 我错过了什么?

模型

class Team < ActiveRecord::Base
  has_many :team_members
  has_many :members, :through => :team_members
end

class Member < ActiveRecord::Base
  has_many :team_members
  has_many :teams, :through => :team_members
end

class TeamMember < ActiveRecord::Base
  belongs_to :teams
  belongs_to :members
end

数据库表

teams
members
teams_members

错误

当我尝试创建具有关联的新记录时,我遇到了以下错误。

@team = Team.new
@team.members
NameError: uninitialized constant Team::Members

同样在搜索现有记录时,会抛出这些错误。

@team = Team.find(1)
@team.members # expecting to get existing records in members table
NameError: uninitialized constant Team::Members

1 个答案:

答案 0 :(得分:0)

TeamMember表的正确名称是team_members而不是teams_members