I'm trying to set up a subscribers/subscriptions (followers/following) relationship for my users with mongoDB. My question is how to access my subscribe method (in model) from the web using a button.
I've set up the model with referenced n-n relationship like this:
class User
include Mongoid::Document
field :username
field :email
has_and_belongs_to_many :subscriptions, class_name: 'User', inverse_of: :subscribers, autosave: true
has_and_belongs_to_many :subscribers, class_name: 'User', inverse_of: :subscriptions
def subscribe!(user)
if self.id != user.id && !self.subscriptions.include?(user)
self.subscriptions << user
end
end
def unsubscribe!(user)
self.subscriptions.delete(user)
end
end
By using pry I have checked that subscribe! method works (which I took from this SO answer HABTM mongoid following/follower).
Pry output showing 1 user subscribing to another
[8] pry(#<User>):2> self.subscribe!(User.first)
=> [#<User _id: Test, username: "Test", email: "test@test.com", subscription_ids: nil, subscriber_ids: ["brownie3003"]>]
[9] pry(#<User>):2> self
=> #<User _id: brownie3003, username: "brownie3003", email: "brownie3003@gmail.com", subscription_ids: ["Test"], subscriber_ids: nil>
Finally I want to add a form to users 'show.html.erb' which is just a button that calls the method in the model. Maybe I need a custom action in the users controller, I'm not really sure. This as far as I got with the form
<%= form_for current_user, :url => {action: 'subscribe'} do |f| %>
<%= f.submit "Subscribe", class: "btn btn-large btn-primary" %>
current_user is a helper method that gets the signed in user.
I've created a subscribe method in Users Controller...
def subscribe
puts "hello"
end
But I'm getting this error
No route matches {:action=>"subscribe", :id=>"beth", :controller=>"users"}
I'm not sure if I'm going about the right way of accessing the method in the model so hopefully someone can advise me on that and explain the best way to allow people to subscribe to each other through the web.
EDIT:
Thanks Kirti for the comment which made me realise I needed to add this line to my routes.rb
match '/subscribe', to: 'users#subscribe', via: 'patch'
Which makes it work now. Not sure on the etiquette of answers so just put it in as an edit, should I answer my own question?