即使存储了正确的Id,belongs_to也不会关联记录

时间:2012-07-28 01:48:21

标签: ruby-on-rails activerecord one-to-one has-and-belongs-to-many

创建用户后,会创建一个团队,并将用户设置为该团队的所有者,并将其设置为该团队的成员。

用户可以是许多团队的成员,团队可以拥有许多成员。 每个用户只能拥有一个团队,团队只能拥有所有者。

现在我得到一些奇怪的行为,我可以弄清楚

1.9.3p194 :001 > user = User.first
User Load (0.1ms)  SELECT "users".* FROM "users" LIMIT 1
=> #<User id: 1, email: "test@example.com", encrypted_password: "$2a$10$KhQ7z3Qb6QXdsBA/MmPLuecrbIV4cGEaMGhIepLjuzla...", reset_password_token: nil, reset_password_sent_at: nil, remember_created_at: nil, sign_in_count: 1, current_sign_in_at: "2012-07-28 01:33:31", last_sign_in_at: "2012-07-28 01:33:31", current_sign_in_ip: "127.0.0.1", last_sign_in_ip: "127.0.0.1", created_at: "2012-07-28 01:33:31", updated_at: "2012-07-28 01:33:31"> 
1.9.3p194 :002 > user.teams
Team Load (0.1ms)  SELECT "teams".* FROM "teams" INNER JOIN "teams_users" ON "teams"."id" = "teams_users"."team_id" WHERE "teams_users"."user_id" = 1
=> [#<Team id: 1, name: "username", dept_no: nil, created_at: "2012-07-28 01:33:31", updated_at: "2012-07-28 01:33:31", user_id: 1>] 
1.9.3p194 :003 > user.owned_team
Team Load (0.2ms)  SELECT "teams".* FROM "teams" WHERE "teams"."user_id" = 1 LIMIT 1
=> #<Team id: 1, name: "username", dept_no: nil, created_at: "2012-07-28 01:33:31", updated_at: "2012-07-28 01:33:31", user_id: 1> 

到目前为止,它都按预期工作,但是当我尝试从另一端访问关联时,没有建立连接。

见下文我已经拿出了与user.owned_team和用户team.owner相同的团队记录,它返回nil

1.9.3p194 :004 > team = Team.first
Team Load (0.1ms)  SELECT "teams".* FROM "teams" LIMIT 1
=> #<Team id: 1, name: "username", dept_no: nil, created_at: "2012-07-28 01:33:31", updated_at: "2012-07-28 01:33:31", user_id: 1> 
1.9.3p194 :005 > team.owner
=> nil 
1.9.3p194 :006 > user.owned_team == team.owner
=> false 
1.9.3p194 :007 > 

User.rb

class User < ActiveRecord::Base

  has_and_belongs_to_many :teams
  has_one :owned_team, :class_name => "Team"

  after_create :set_user_on_team

  private

  def set_user_on_team
    self.owned_team = self.teams.create(:name => 'username' ) 
  end
end

Team.rb

class Team < ActiveRecord::Base

  attr_accessible :name
  has_and_belongs_to_many :users
  belongs_to :owner, :class_name => "User"

end

1 个答案:

答案 0 :(得分:1)

我认为你错过了某处的外键声明。

假设您在团队表中有owner_id字段:

class User < ActiveRecord::Base
  has_one :owned_team, :class_name => "Team", :foreign_key => 'owner_id'
end

class Team < ActiveRecord::Base
  belongs_to :owner, :class_name => "User", :foreign_key => 'owner_id'
end

这种方式rails知道如何在访问两个链接时提取数据