开发者

Accessing two sides of a user-user relationship in rails

开发者 https://www.devze.com 2022-12-28 22:18 出处:网络
Basically, I have a users model in my rails app, and a fanship model, to facilitate the ability for users to become \'fans\' of each other.

Basically, I have a users model in my rails app, and a fanship model, to facilitate the ability for users to become 'fans' of each other.

In my user model, I have:

has_many :fanships
has_many :fanofs, :through => :fanships

In my fanship model, I have:

belongs_to :user
belongs_to :fanof, :class_name => "User", :foreign_key => "fanof_id"

My fanship table basically consists of :id, :user_id and :fanof_id. This all works fine, and I can see what users a specific user is a fan of like:

<% @user.fanofs.each do |fan| %>
    #things
<% end %>

My question is, how can I get a list of the users that are a fan of this specific user?

I'd like it if I could just have something like @user.fans, but if th开发者_StackOverflowat isn't possible what is the most efficient way of going about this?

Thanks!


Add in User model:

has_many :my_fanclubs, :class_name => 'Fanship', :foreign_key => 'fanof_id'
has_many :fans, :through => :my_fanclubs, :source => :user, :class_name => 'User'

(not tested)

0

精彩评论

暂无评论...
验证码 换一张
取 消