Ruby on Rails - 跟随关系的用户

时间:2015-03-27 00:45:34

标签: ruby-on-rails

我正在创建我的第一个Rails应用程序,我想要一个非常基本的用户系统(尚未进行验证考虑),其中一个用户可以关注另一个类似于Twitter或Instagram的用户。

之前搜索了stackoverflow之后,我在YouTube上发现了以下视频,并尝试按照他们的说明继续操作。我已将下面的链接作为参考。

https://www.youtube.com/watch?v=jSUWu50XK48

我编写了以下类,并编写了以下迁移,以便将这些添加到我的数据库中。虽然视频中没有找到迁移,但我认为我的部分问题可能还在于迁移类。

class User < ActiveRecord::Base
    has_secure_password

    has_many :posts
    has_many :followers, through: :followings
end

class Following < ActiveRecord::Base
    belongs_to :user
    belongs_to :follower, class_name: 'User'
end

class CreateFollowings < ActiveRecord::Migration
    def change
        create_table :followings do |t|
            t.integer       :user_id
            t.integer       :follower_id
            t.timestamps
        end
    end
end

运行rake db:drop db:migrate后,我的数据库按照我的预期填写了表格,但是我也尝试在rake db:seed文件中写下以下内容后运行seeds.rb

jerry = User.create( :name => "jerry", :email => "jerry@seinfeld.com", :password => "newman" )
george = User.create( :name => "george", :email => "george@costanza.com", :password => "bosco" )
elaine = User.create( :name => "elaine", :email => "elaine@benes.com", :password => "dance" )
kramer = User.create( :name => "kramer", :email => "cozmo@kramer.com", :password => "bagels" )

kramer.following.create(follower: jerry)

我尝试在最后一个following方法中复制followings.create(),但两次我的控制台中的错误都是&#34; NoMethodError:未定义的方法&#39;关注& #39;

如果有人可以在这里提供帮助,我将不胜感激!

1 个答案:

答案 0 :(得分:0)

您缺少以下内容:

    {li> has_many :followingsUser课程中。

班级定义:

class User < ActiveRecord::Base
  ...
  has_many :followings
  has_many :followers, through: :followings
  ...
end

class class Following < ActiveRecord::Base
  belongs_to :user
  belongs_to :follower, class_name: 'User'
end

运行迁移以创建followings表后,您应该可以从控制台执行以下操作:

> jerry = User.create( :name => "jerry", :email => "jerry@seinfeld.com", :password => "newman" )
> george = User.create( :name => "george", :email => "george@costanza.com", :password => "bosco" )
> elaine = User.create( :name => "elaine", :email => "elaine@benes.com", :password => "dance" )
> kramer = User.create( :name => "kramer", :email => "cozmo@kramer.com", :password => "bagels" )

> kramer.followers
=> #<ActiveRecord::Associations::CollectionProxy []>
> kramer.followers.count
=> 0
> kramer.followers << george

> kramer.followers.count
=> 1
> kramer.followers.map(&:name)
> ["george"]