我在这里有两种不同类型的用户,粉丝和艺术家。
我有一个关系模型,允许粉丝关注艺术家。
创建关系工作正常,但我现在需要检查粉丝是否关注艺术家。
我的数据库中也有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%的错误出现在我的&#34;跟随?&#34;方法
答案 0 :(得分:2)
正如Jordan Dedels所说,这将有效:
def following?(artist)
artists.include?(artist)
end
但它强制rails加载连接模型,或使用连接查询。 如果您知道关联的结构,并且只需要布尔值(true / false),那么这个更快:
def following?(artist)
Relationship.exists? fan_id: id, artist_id: artist.id
end
答案 1 :(得分:1)
在Fan
模型中,尝试:
def following?(artist)
artists.include?(artist)
end