Reputation: 786
My application has Dwellings
and Roomies
. I am building some authentication into the Dwelling
view - only users
who are roomies
of the current dwelling
should be able to view certain data - all other users will see a different view.
To enable this, I have created an is_roomie?
method in the Users Controller
. The method looks like this:
## is_roomie? method in Users_Controller.rb ##
def is_roomie?
roomie_ids = []
@dwelling.roomies.each do |r|
roomies_ids << r.id
end
roomie_ids.include?(current_user.id)
end
I call this method in the Dwelling
view as follows:
## show.html.erb (Dwelling) ##
....
<% if current_user && current_user.is_roomie? %>
....
When I loaded the page after implementing this, I get the following NoMethoderror:
NoMethodError in Dwellings#show
Showing >/Volumes/UserData/Users/jraczak/Desktop/Everything/rails_projects/Roomie/roomie/app/views/dwellings/show.html.erb where line #5 raised:
undefined method `is_roomie?' for #User:0x00000102db4608>
For some background, I did try this as a Dwelling
method and moved this into the User
model to no avail. Thanks in advance for any and all insight!
Upvotes: 1
Views: 148
Reputation: 6111
The current_user object does not have a method is_roomie?. This is a method in your controller. You can call the method in your show action and make it available for the view like so:
#in UsersController.rb
def show
@is_roomie = is_roomie?
end
Upvotes: 0
Reputation: 1725
current_user
is a User
object, not a UsersController
object, so you cannot call the method you've defined on that object. When you think about it in this context, you'll see that you should define this method on User
.
Try something like this in app/model/user.rb:
class User < ActiveRecord::Base
# ...
def roomie?(dwelling)
dwelling.roomies.include?(self)
end
end
Looking at this, though, we can improve the code by moving it into the Dwelling class in app/models/dwelling.rb:
class Dwelling < ActiveRecord::Base
# ...
def roomie?(user)
roomies.include?(user)
end
end
You would then use this in the view with:
<% if current_user && @dwelling.roomie?(current_user) %>
Upvotes: 2