在两种用户类型之间创建 "following?" 方法,rails
Creating a "following?" method between two user types, rails
我这里有两种不同类型的用户,粉丝和艺术家。
我有一个关系模型可以让粉丝关注艺术家。
创建关系工作正常,但我现在需要检查粉丝是否在关注艺术家。
我的数据库中也有 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% 的错误是在我的 "following?" 方法中。
在您的 Fan
模型中,尝试:
def following?(artist)
artists.include?(artist)
end
正如 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
我这里有两种不同类型的用户,粉丝和艺术家。
我有一个关系模型可以让粉丝关注艺术家。
创建关系工作正常,但我现在需要检查粉丝是否在关注艺术家。
我的数据库中也有 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% 的错误是在我的 "following?" 方法中。
在您的 Fan
模型中,尝试:
def following?(artist)
artists.include?(artist)
end
正如 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