Reputation: 13
so I have 2 methods in one of my models. The model name is user.rb, and the class is User. Here are the methods I declared
def follow(user_id)
following_relationships.create(following_id: user_id)
end
def unfollow(user_id)
following_relationships.find_by(following_id: user_id).destroy
end
And in my view I have a link_to that method like this:
= link_to 'Following', unfollow_user_path, remote: true
It is HAML but that shouldn't make a difference. When I start the server and try to go to someone's page I get this error:
undefined local variable or method `unfollow_user_path' for #<#:0x00563935a456e0>
This shouldn't be happening because I declared the method in the user model.
Any help would be appreciated, thank you.
Upvotes: 0
Views: 101
Reputation: 131
Yar is here.
What you trying to do in your example is to call model's method by ajax request, but it's not how it works. When you send AJAX or whatever request it first matches routes defined in routes.rb
and finds corresponding controller's method to be called. So, you need to do this steps
0) Read about MVC and rails here or any other source you like http://guides.rubyonrails.org/getting_started.html
1) create new controller's methods which should be called when you follow/unfollow
2) add corresponding routes to routes.rb
file like @Doon mentioned
3) inside this controller methods you can call your model methods
Upvotes: 0
Reputation: 20232
Functions defined in models have 0 effect on routing, you would need to modify your routes and your user controller to make this work.
you would need something similar to this.
#config/routes.rb
resources :users do
member do
post :unfollow
post :follow
end
end
and then add ControllerActions for #follow
and #unfollow
to get the data from the view, and actually call the functions on the model.
read the rails routing tutorial (http://guides.rubyonrails.org/routing.html) for more information
Upvotes: 2