如何:“访问过您个人资料的用户......”

时间:2009-03-13 16:37:51

标签: ruby-on-rails

我想向每个访问过她/他的用户个人资料的用户显示。起初看起来很简单,acts-as-readable插件可以完成我需要的一切。但是,此插件不适用于用户模型。

如果将来我决定将访问者添加到文章,专辑等中,该怎么办?

/usr/local/lib/ruby/gems/1.8/gems/activerecord-2.2.2/lib/active_record/base.rb:1833:in `method_missing': undefined local variable or method `acts_as_readable' for #<Class:0xb70d1bfc> (NameError)
        from /home/www/ror/app/models/user.rb:22
        from /usr/local/lib/ruby/gems/1.8/gems/activesupport-2.2.2/lib/active_support/dependencies.rb:382:in `load_without_new_constant_marking'
        from /usr/local/lib/ruby/gems/1.8/gems/activesupport-2.2.2/lib/active_support/dependencies.rb:382:in `load_file'
        from /usr/local/lib/ruby/gems/1.8/gems/activesupport-2.2.2/lib/active_support/dependencies.rb:521:in `new_constants_in'
        from /usr/local/lib/ruby/gems/1.8/gems/activesupport-2.2.2/lib/active_support/dependencies.rb:381:in `load_file'
        from /usr/local/lib/ruby/gems/1.8/gems/activesupport-2.2.2/lib/active_support/dependencies.rb:256:in `require_or_load'
        from /usr/local/lib/ruby/gems/1.8/gems/activesupport-2.2.2/lib/active_support/dependencies.rb:427:in `load_missing_constant'
        from /usr/local/lib/ruby/gems/1.8/gems/activesupport-2.2.2/lib/active_support/dependencies.rb:77:in `const_missing'
         ... 31 levels...
        from /usr/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/bin/../lib/mongrel/command.rb:212:in `run'
        from /usr/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/bin/mongrel_rails:281
        from /usr/local/bin/mongrel_rails:19:in `load'
        from /usr/local/bin/mongrel_rails:19

有谁知道一个可以做到这一点的alternativ插件? (user1.users_who_read等)遗憾的是act-as-readable在用户模型中不起作用。将此功能放入选定的模型非常有用。

祝你好运。 AsbjørnMorell。

2 个答案:

答案 0 :(得分:3)

为什么不自己动手?

class User < ActiveRecord::Base
  has_many :user_visits
  has_many :visitors, :through => :user_visits, :source => :visitor
end

class UserVisit < ActiveRecord::Base
  # user_id :integer
  # visitor_id :integer
  # visited_at :datetime

  belongs_to :user
  belongs_to :visitor, :foreign_key => 'visitor_id', :class_name => 'User'
end


User.first.visitors = [user_1, user2]

你可以使用STI,你将拥有那么多* vists连接表。 YMMV因为它使诸如缓存之类的事情复杂化。如果它能带来更快的体验,我宁愿在代码方面有一点“湿润”。

答案 1 :(得分:1)

嗯,这真的给了我一些问题:

User.first.visitors
ActiveRecord::HasManyThroughSourceAssociationNotFoundError: 
Could not find the source association(s) :visitor or :visitors in model UserVisit.  
Try 'has_many :visitors, :through => :user_visits, :source => <name>'.  
Is it one of :user?

我尝试添加:source =&gt; :用户到我的用户模型。然而,在执行user.visitors时,我只获得所有者。

这是我的迁移:

class CreateUserVisits < ActiveRecord::Migration
    def self.up
        create_table :user_visits do |t|
            t.integer :user_id
            t.integer :visit_id
        end
    end

    def self.down
    drop_table :user_visits
    end
end

有什么想法吗?