I use ruby '2.5.0', rails, '5.2.2', mongoid '7.0.2' and devise
I try to add follow function, but I have this error in mongoid '7.0.2'
message: Ambiguous relations
@options={:class_name=>"User"}, @extension=nil, @module_path="", @polymorphic=false, @default_foreign_key_field="follower_id", @foreign_key="follower_id", @indexed=false, @class_name="User", @klass=User, @validate=false>,
@options={:class_name=>"User"}, @extension=nil, @module_path="", @polymorphic=false, @default_foreign_key_field="followed_id", @foreign_key="followed_id", @indexed=false, @class_name="User", @klass=User, @validate=false> defined on Relationship. summary: When Mongoid attempts to set an inverse document of a relation in memory, it needs to know which relation it belongs to. When setting :relationships, Mongoid looked on the class User for a matching relation, but multiples were found that could potentially match:
@options={:class_name=>"User"}, @extension=nil, @module_path="", @polymorphic=false, @default_foreign_key_field="follower_id", @foreign_key="follower_id", @indexed=false, @class_name="User", @klass=User, @validate=false>,
@options={:class_name=>"User"}, @extension=nil, @module_path="", @polymorphic=false, @default_foreign_key_field="followed_id", @foreign_key="followed_id", @indexed=false, @class_name="User", @klass=User, @validate=false>. resolution: On the :relationships relation on User you must add an :inverse_of option to specify the exact relationship on Relationship that is the opposite of :relationships.
user.rb
class User
include Mongoid::Document
field :email, type: String, default: ""
has_many :relationships, foreign_key: "follower_id", dependent: :destroy
has_many :reverse_relationships, foreign_key: "followed_id", class_name: "Relationship", dependent: :destroy
def retrieve_users_for_ids(user_ids)
users = []
User.in(id: user_ids).each do |user|
users << user
end
users
end
def followed_users
user_ids = []
relationships.each do |relationship|
user_ids << relationship.followed_id
end
return retrieve_users_for_ids(user_ids)
end
def followers
user_ids = []
reverse_relationships.each do |relationship|
user_ids << relationship.follower_id
end
return retrieve_users_for_ids(user_ids)
end
def following?(other_user)
relationships.where(followed_id: other_user.id).first
end
def follow!(other_user)
relationships.create!(followed_id: other_user.id)
end
def unfollow!(other_user)
relationships.where(followed_id: other_user.id).first.destroy
end
end
_follow.html.erb
<%= form_for(current_user.relationships.build(followed_id: @user.id),
remote: true) do |f| %>
<%= f.hidden_field :followed_id %>
<%= f.submit 'Follow', data: {disable_with: 'Follow...'}, class: 'btn btn-d' %>
<% end %>