Alex Heil
Alex Heil

Reputation: 345

Creating a "following?" method between two user types, rails

I've got two different types of users here, Fans and Artists.

I have a Relationships model to allow Fans to follow Artists.

Creating the relationship is working fine, but I now need to check if a Fan is following an Artist.

I also have add_index :relationships, [:fan_id, :artist_id], unique: true in my database, so a Fan cannot follow an Artist multiple times and displays an error if they try to follow again.

Now when a Fan clicks the follow button I want an unfollow button to show. To display this I need to check if a Fan is following an Artist.

Here is my code:

### 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 %>

I'm 100 percent the error is in my "following?" method.

Upvotes: 0

Views: 68

Answers (2)

tompave
tompave

Reputation: 12427

As Jordan Dedels said, this will work:

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

But it forces rails to either load the join models, or to use a join query. If you know the structure of your associations, and you only want a boolean (true/false), then this is faster:

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

Upvotes: 2

Jordan Allan
Jordan Allan

Reputation: 4486

Inside your Fan model, try:

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

Upvotes: 1

Related Questions