Rails 5.0第14章Micheal Hartl教程未定义局部变量active_relationship

时间:2017-06-27 21:53:01

标签: ruby-on-rails-5 railstutorial.org relationships

基本上我一直在关注Rails教程(我遇到了很多问题,但大多数都很容易解决)但是我现在刚刚开始这一章并且我正在运行一个问题

以下是教程的link(在表14.1练习2之后),由于未定义变量,我目前在练习时被阻止。

irb(main):035:0> active_relationship.follower \r
NameError: undefined local variable or method `active_relationship' for main:Object
    from (irb):35

我并不完全明白我在做什么,但我知道我们正在尝试通过has_many:belongs_to:创建的关系,从而创建关系。

   irb(main):021:0> user.active_relationships.create!(followed_id: 2)\r
   (0.1ms)  begin transaction
  User Load (0.1ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT ?  [["id", 1], ["LIMIT", 1]]
  User Load (0.0ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT ?  [["id", 2], ["LIMIT", 1]]
  SQL (0.3ms)  INSERT INTO "relationships" ("follower_id", "followed_id", "created_at", "updated_at") VALUES (?, ?, ?, ?)  [["follower_id", 1], ["followed_id", 2], ["created_at", 2017-06-27 20:49:11 UTC], ["updated_at", 2017-06-27 20:49:11 UTC]]
   (57.3ms)  commit transaction
=> #<Relationship id: 1, follower_id: 1, followed_id: 2, created_at: "2017-06-27 20:49:11", updated_at: "2017-06-27 20:49:11">

以下是新创建的文件的内容:

应用程序/模型/ relationship.rb

class Relationship < ApplicationRecord
  belongs_to :follower, class_name: "User"
  belongs_to :followed, class_name: "User"
end

应用程序/模型/ user.rb

class User < ApplicationRecord
  has_many :microposts, dependent: :destroy
  has_many :active_relationships, class_name:  "Relationship",
           foreign_key: "follower_id",
           dependent: :destroy
.
.
.

问题在于:我不明白为什么变量(active_relationship)没有定义但在控制台内调用Relationships.all显示了这个:

#<ActiveRecord::Relation [#<Relationship id: 1, follower_id: 1, followed_id: 2, created_at: "2017-06-27 20:49:11", updated_at: "2017-06-27 20:49:11">]>

因此意味着创建并存储了关系,因此应该可以通过方法active_relationship.followedactive_relationship.follower访问它。 但它们没有定义,我不知道它们为什么不是。 如果需要更多信息只需要它,我会很高兴它能帮助我解决这个小问题。

1 个答案:

答案 0 :(得分:3)

您可以使用user.active_relationships来访问关系元素,user.active_relationships.create是一系列关系(关注者/关注关系),或者您可以将active_relationship的结果存储为active_relationship }。

您的问题是create在您的上下文中未定义,教程必须假设您根据# app/models/model.rb class Model < ActiveRecord::Base after_create :some_call def some_call puts "this is your code after record added?" # you can also check table condition directly from here puts Model.count end end 的返回值或通过访问关系数组来存储此值。