2015-02-07 65 views
0

我有两种不同类型的用户,粉丝和艺术家。创建“跟随?”方法之间的两种用户类型,轨道

我有一个关系模式,让球迷跟随艺术家。

创建关系,工作正常,但我现在需要检查,如果一个风扇以下的艺术家。

我也有add_index :relationships, [:fan_id, :artist_id], unique: true在我的数据库,所以人都可以不遵循一个艺术家多次,如果他们试图再次跟随显示错误。

现在,当粉丝点击关注按钮我想要一个取消关注按钮来显示。为了显示这个,我需要检查一个粉丝是否关注一个艺术家。

这里是我的代码:

### model/artist.rb ### 

class Artist < ActiveRecord::Base 

    has_many :relationships 
    has_many :fans, through: :relationships 
    belongs_to :fan 

end 

### model/fan.rb ### 

class Fan< ActiveRecord::Base 

    has_many :relationships 
    has_many :artists, through: :relationships 
    belongs_to :artist 

    def following?(artist) 
    Fan.includes(artist) 
    end 

end 

### relationship.rb ### 

class Relationship < ActiveRecord::Base 
    belongs_to :fan 
    belongs_to :artist 
end 

### views/artists/show.html.erb ### 

<% if current_fan.following?(@artist) %> 
    unfollow button 
<% else %> 
    follow button 
<% end %> 

我是100%的错误是在我的 “下面?”方法。

+0

可以ü尝试:relationships.find_by(artist_id:artist.id)在以下?方法 – C404 2015-02-07 00:16:52

回答

2

乔丹Dedels说,这将工作:

def following?(artist) 
    artists.include?(artist) 
end 

但它迫使轨要么加载加盟模式,或使用连接查询。 如果你知道你的协会的结构,你只想要一个布尔值(真/假),那么这是更快:

def following?(artist) 
    Relationship.exists? fan_id: id, artist_id: artist.id 
end 
+0

加1,绕过连接。 – 2015-02-07 01:10:11

1

里面你Fan模式,尝试:

def following?(artist) 
    artists.include?(artist) 
end 
相关问题