Rails教程第12章 - 遵循!()方法不起作用

时间:2012-10-22 11:35:54

标签: ruby-on-rails model associations

我是Rails的新手,并且认为我已经设法通过Michael Hartl的教程(RoR3 ed1)直接找到了帮助,但我终于难倒了。任何人都可以提出任何建议吗?

我的问题在于12.1节中的Users模型的follow!()方法。当我将用户传递给方法并尝试将foreignID存储在关系中时,它将以nil。

的形式出现
1.9.2p290 :023 > user1=User.find(1)
  User Load (0.3ms)  SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1  [["id", 1]]
 => #<User id: 1, name: "Example User", email: "example@railstutorial.org", created_at: "2012-10-20 18:48:38", updated_at: "2012-10-20 18:48:38", encrypted_password: "cd8e8ad53b1157789cb004de14bc14112786981004b51bd1576...", salt: "d947c9bcb6563fd8c70d3d1c64c9d82507a89b936ea0cbfd3e4...", admin: false> 
1.9.2p290 :024 > user2=User.find(4)
  User Load (0.3ms)  SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1  [["id", 4]]
 => #<User id: 4, name: "Mrs. Carmelo Witting", email: "example-2@railstutorial.org", created_at: "2012-10-20 18:48:38", updated_at: "2012-10-20 18:48:38", encrypted_password: "c0f2c8f998bc1b9bf76c9196176828dc543ceeb2a28f7b81c2d...", salt: "3c134e8fd391db0b9b21f0e08ddda7bfd8d16b3abe6726d517d...", admin: false> 
1.9.2p290 :025 > user1.follow!(user2)
  SQL (1.9ms)  INSERT INTO "relationships" ("created_at", "followed_id", "follower_id", "updated_at") VALUES (?, ?, ?, ?)  [["created_at", Mon, 22 Oct 2012 11:16:38 UTC +00:00], ["followed_id", nil], ["follower_id", 1], ["updated_at", Mon, 22 Oct 2012 11:16:38 UTC +00:00]]
 => #<Relationship id: 8, follower_id: 1, followed_id: nil, created_at: "2012-10-22 11:16:38", updated_at: "2012-10-22 11:16:38"> 

以下是用户模型的相关位。可能导致这种情况的原因是什么?

class User < ActiveRecord::Base
.
.
  has_many :relationships, :foreign_key => "follower_id",
                           :dependent => :destroy
  has_many :following, :through => :relationships, :source => :followed
.
  def follow!(followed)
    relationships.create!(:followed_id => followed.id)
  end

end

1 个答案:

答案 0 :(得分:0)

解决了这个问题。我在关系模型中为follow_id编写了attr_accessor而不是attr_accessible。

卫生署