Rails 自引用实现最近来访

Posted by wxianfeng Mon, 12 Oct 2009 04:33:00 GMT

环境 : ruby 1.8.6 + rails 2.1.0 + ubuntu 8.10

效果:就像 xiaonei 这样

snapshot30

当然最简单的办法 你可以 直接sql操作就ok 了。。。我这里介绍 利用 rails的 activerecord自引用 解决,一个系统有一个users表,但是每一个user可能有friends 或者 followers , 而这个 friends 和 followers 也在 users这个表里,这样就需要 用到 rails的自引用了。

实现最近来访 只是实现了一层的 相当于 取出 twitter的 followers

表结构:

1,用户表 client_infos (username,password,........)

2,访问关系表 vistorships

snapshot31

model关系

class ClientInfo < ActiveRecord::Base
 has_many :vistorships  
 has_many :vistors, :through => :vistorships
end
class Vistorship < ActiveRecord::Base 
 belongs_to :client_info   
belongs_to :vistor, :class_name => "ClientInfo"
end

添加最近来访 数据:

    @client_info = ClientInfo.find(params[:id])
    @recentvistor = @client_info.vistorships.build( :vistor => current_client_info)
    @recentvistor.save

取出全部来访 数据

@client_info.vistorships

Model 取出最近来访的12个vistor

    def get_vistors(client_info) # client_info 是显示那个人的对象
      find(:all,
        :conditions => ["client_info_id = ? and vistor_id <> ?" , client_info.id , client_info.id],
        :select => ["distinct(vistor_id)"],
        :limit => 12,
        :order => 'created_at DESC'
      )
    end

controller中取出数据

@latestvistors = Vistorship.get_vistors(@client_info)

View中输出

<ul>
        <%- for lvistor in @latestvistors -%>
<li>
            <%= image_link lvistor.vistor, :image => :thumbnail , :class => 'image' %>
            <%= client_info_link lvistor.vistor, :class => 'name' %>
          </li>

        <%- end -%>
      </ul>

ref:

http://railscasts.com/episodes/163-self-referential-association

This entry was posted on Mon, 12 Oct 2009 04:33:00 GMT and Posted in . You can follow any any response to this entry through the Atom feed. You can leave a comment or a trackback from your own site.

Tags


Trackbacks

Use the following link to trackback from your own site:
http://wxianfeng.com/trackbacks?article_id=4

Comments

Leave a comment