2

I'm new to Rails, and thought I'd managed to get right through Michael Hartl's tutorial (RoR3 ed1) without asking for help, but I'm finally stumped. Can anyone offer any suggestions?

My problem is with the follow!() method of the Users model in section 12.1. When I pass a user to the method and try to store the foreignID in the relationship it comes through as 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"> 

Here are the relevant bits of the user model. What might be causing this?

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
4

1 回答 1

0

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

多哈

于 2012-10-22T18:27:59.757 回答